Stack.Push() Method in C#
Last Updated :
04 Feb, 2019
This method(comes under System.Collections namespace) is used to inserts an object at the top of the Stack. If the Count already equals the capacity, the capacity of the Stack is increased by automatically reallocating the internal array, and the existing elements are copied to the new array before the new element is added. If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count.
Syntax:
public virtual void Push (object obj);
Example:
using System;
using System.Collections;
class GFG {
public static void Main()
{
Stack myStack = new Stack();
myStack.Push( "one" );
Console.Write( "Total number of elements " +
"in the Stack are : " );
Console.WriteLine(myStack.Count);
myStack.Push( "two" );
Console.Write( "Total number of elements" +
" in the Stack are : " );
Console.WriteLine(myStack.Count);
myStack.Push( "three" );
Console.Write( "Total number of elements" +
" in the Stack are : " );
Console.WriteLine(myStack.Count);
myStack.Push( "four" );
Console.Write( "Total number of elements" +
" in the Stack are : " );
Console.WriteLine(myStack.Count);
myStack.Push( "five" );
Console.Write( "Total number of elements" +
" in the Stack are : " );
Console.WriteLine(myStack.Count);
myStack.Push( "six" );
Console.Write( "Total number of elements" +
" in the Stack are : " );
Console.WriteLine(myStack.Count);
}
}
|
Output:
Total number of elements in the Stack are : 1
Total number of elements in the Stack are : 2
Total number of elements in the Stack are : 3
Total number of elements in the Stack are : 4
Total number of elements in the Stack are : 5
Total number of elements in the Stack are : 6
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...