Stack in C
Stack in C
Method Usage
Push(T) Inserts an item at the top of the
stack.
Peek() Returns the top item from the stack.
Pop() Removes and returns items from the
top of the stack.
Contains(T) Checks whether an item exists in the
stack or not.
Clear() Removes all items from the stack.
Pop()
The Pop() method returns the last element and removes it
from a stack. If a stack is empty, then it will throw the
InvalidOperationException. So, always check for the
number of elements in a stack before calling the Pop()
method.
Example: Access Stack using Pop()
Stack<int> stack1 = new Stack<int>();
stack1.Push(1);
stack1.Push(2);
stack1.Push(3);
stack1.Push(4);
Console.Write("Number of elements in Stack: {0}", stack1.Count);
if(stack1.Count > 0)
{
Console.WriteLine(stack1.Peek());
Console.WriteLine(stack1.Peek());
}
Example: Contains()
Stack<int> stack1 = new Stack<int>();
stack1.Push(1);
stack1.Push(2);
stack1.Push(3);
stack1.Push(4);
stack1.Contains(2);
stack1.Contains(10);