In this article, we will learn about the stack class in C#.
A stack represents a variable size last-in-first-out (LIFO) collection of instances of the same specified type.
Three main operations can be performed on a stack and its elements:
<ul><li>Push inserts an element at the top of the Stack.</li>
<li>Pop removes an element from the top of the Stack.</li>
<li>Peek returns an element that is at the top of the Stack but does not remove it from the Stack.<li>
</ul>
<h4>Creating a Stack</h4>
<p>We create a Stack in C# using the following syntax:
Stack<T> st = new Stack<T>();
<T>
here denotes any datatype which we want to create a stack of.
Count
: This property gets the number of elements present in the stack.Push(T)
: Inserts an object at the top of the StackPop()
: Removes and returns the object at the top of the StackPeek()
: Returns the object at the top of the StackContains(T)
: Determines whether an element is in the StackClear()
: Removes all objects from the StackDifferent Stack operations are demonstrated in the example below:
using System;
using System.Collections.Generic;
namespace StackDemo {
class Example {
static void Main(string[] args) {
Stack st = new Stack ();
st.Push(5);
st.Push(5);
st.Push(2);
st.Push(9);
Console.WriteLine(st.Count); // Prints 4, the size of stack
Console.WriteLine(st.Peek()); // Prints 9, the top element
Console.WriteLine(st.Pop()); // Prints 9, then removes it
Console.WriteLine(st.Pop()); // Prints 2, then removes it
Console.WriteLine(st.Contains(5)); // Checks if 5 is present
Console.WriteLine(st.Contains(2)); // Checks if 2 is present
}
}
}
</code></pre>
Output:
4
9
9
2
True
False
Task
In the editor below, perform the different tasks as directed.