Home  >  Article  >  Backend Development  >  Push and pop in stack class in C#

Push and pop in stack class in C#

WBOY
WBOYforward
2023-08-27 11:05:04881browse

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');

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 + " ");
         }
      }
   }
}

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete