Home > Backend Development > C#.Net Tutorial > Push and pop in stack class in C#

Push and pop in stack class in C#

WBOY
Release: 2023-08-27 11:05:04
forward
970 people have browsed it

C# 中堆栈类中的压入与弹出

The Stack class represents a last-in-first-out collection of objects. You can use this when you need LIFO access to your project.

The following are the properties of the Stack class -

  • Count - Get the number of elements in the stack.

Push operation

Use the following command to add an element in the stack Push operation-

Stack st = new Stack();

st.Push('A');
st.Push('B');
st.Push('C');
st.Push('D');
Copy after login

Pop operation

Pop operation from the stack Elements at the top start removing elements.

The following example shows how to use the Stack class and its Push( ) and Pop() methods -

Using System;
using System.Collections;

namespace CollectionsApplication {
   class Program {
      static void Main(string[] args) {
         Stack st = new Stack();

         st.Push('A');
         st.Push('B');
         st.Push('C');
         st.Push('D');

         Console.WriteLine("Current stack: ");
         foreach (char c in st) {
            Console.Write(c + " ");
         }
         Console.WriteLine();

         st.Push('P');
         st.Push('Q');
         Console.WriteLine("The next poppable value in stack: {0}", st.Peek());
         Console.WriteLine("Current stack: ");

         foreach (char c in st) {
            Console.Write(c + " ");
         }

         Console.WriteLine();
         Console.WriteLine("Removing values....");
         st.Pop();
         st.Pop();
         st.Pop();
         Console.WriteLine("Current stack: ");
         foreach (char c in st) {
            Console.Write(c + " ");
         }
      }
   }
}
Copy after login

The above is the detailed content of Push and pop in stack class in C#. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template