Home >Backend Development >C#.Net Tutorial >Implementing a stack in C#

Implementing a stack in C#

WBOY
WBOYforward
2023-09-07 16:17:10885browse

在 C# 中实现堆栈

The Stack class is implemented in C# using Push and Pop operations.

Stack is used in C# to represent a last-in-first-out collection of objects. The following are the methods of the Stack class-

##Sr.No.Methods and descriptions1234 56
public virtual void Clear();Removes all elements from the stack.

public virtual bool Contains(object obj);Determine whether the element is in in the stack.

public virtual object Peek();Returns the object at the top of the Stack Don't delete it.

Public virtual object Pop();Delete and return the top of the stack object.

public virtual void Push(object obj);Insert at the top of the stack an object.

td>

Public virtual object[] ToArray(); strong>Copy Stack to new array.

Push operation adds an element.

Push operation adds an element. p>

Stack st = new Stack();
st.Push('A');
st.Push('B');
st.Push('C');
st.Push('D');

The pop operation removes elements from the stack.

st.Push('P');
st.Push('Q');

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

Example

Real-time demonstration

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

Output

Current stack:
D C B A
The next poppable value in stack: Q
Current stack:
Q P D C B A
Removing values....
Current stack:
C B A

The above is the detailed content of Implementing a stack 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