Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
stack
push
communitycreator

How to push an element to a stack in C#

Surabhi Sharma

The Stack<T> generic class in the System.Collections.Generic namespace provides the Push() method, which inserts an element to the top of a stack in C#.

Syntax

public void Push (T item);
  • This method takes the value T as input to be pushed onto the Stack<T>.
  • The value T can be null for reference types.

Things to Note

  • The Stack<T> class internally uses an array to store the elements.

  • This method is an O(1) operation if the number of elements in the stack is less than its capacity.

  • When we add a new element using Push(), and the current count of elements in the stack is equal to its capacity, a new array double the size of the initial capacity is allocated. Existing elements are copied over to the new array. After that, the new element is added to the stack.

  • When the count of elements is equal to the capacity, Push() method is an O(n) operation, where n is the count of the elements.

Adding an item to top of stack using Push() method

Code

In the following code, we have created a stack of strings.

First, we call the Push() method with the Asia string and then the Africa string. This inserts both strings onto the stack, with Africa at the top of the stack.

We then show all the stack elements, and we can see that it has Africa at the top, followed by Asia.

We again call the Push() method with the Europe string as input, and it inserts Europe at the top of the stack. This stack is a LIFOLast In First Out data structure.

Later, we again display all elements of the stack and can observe that Europe is at the top of the stack.

The program below shows the output and exits.

Current Stack Items: 
Africa, Asia

Pushing 'Europe' to the Stack..

Stack Items:
Europe, Africa, Asia
using System;
using System.Collections.Generic;

class StackPush
{
    static void Main()
    {
        Stack<string> stack = new Stack<string>();
        stack.Push("Asia");
        stack.Push("Africa");     

        Console.WriteLine("Current Stack Items: \n{0}\n", string.Join(",", stack.ToArray()));
        Console.WriteLine("Pushing 'Europe' to the Stack..\n");
        stack.Push("Europe");
        Console.WriteLine("Stack Items:\n{0}", string.Join(",", stack.ToArray()));

    }
}

RELATED TAGS

c#
stack
push
communitycreator
RELATED COURSES

View all Courses

Keep Exploring