The Stack<T>.Push(T) method in C# adds an element to a stack. Since a stack follows the Last-In, First-Out (LIFO) principle, the newly added element becomes the next element to be removed.
- Push() adds one element to the stack.
- The Count property increases by one after each successful Push() operation.
using System;
using System.Collections.Generic;
class GFG{
public static void Main(){
Stack<string> myStack = new Stack<string>();
myStack.Push("one");
myStack.Push("two");
myStack.Push("three");
myStack.Push("four");
Console.WriteLine("Number of elements: " + myStack.Count);
Console.WriteLine("Elements in the Stack:");
foreach (string item in myStack)
{
Console.WriteLine(item);
}
}
}
Output
Number of elements: 4 Elements in the Stack: four three two one
Explanation: The elements are added in the order "one", "two", "three", and "four". Because Stack<T> follows LIFO order, enumeration starts with "four", the most recently pushed element.
Syntax
public void Push(T item);
- Parameter: item: The element to add to the Stack<T>.
- Return Value: The Push() method does not return a value.
How Push() Works
Suppose the following elements are pushed into a stack:
Push("one")
Push("two")
Push("three")
The stack will contain:
three ← Next to be removed
two
one
Since "three" was added last, it will be the first element removed by a Pop() operation.
Push() vs Pop()
| Push() | Pop() |
|---|---|
| Adds an element to the stack | Removes and returns the next element |
| Increases Count by one | Decreases Count by one |
| Accepts an element as a parameter | Does not require an element parameter |
| Normally O(1) | O(1) |