Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
pop
communitycreator

How to remove an element from the top of a stack in C#

Surabhi Sharma

The Stack<T> generic class in the System.Collections.Generic namespace provides the Pop() method, which can be used to remove and return the element present at the top of a stack in C#.

Syntax

public T Pop ();
  • This method removes and returns the value of T type present at the top of the stack.

Things to note

  • This method is an O(1)O(1) operation.
  • It modifies the state of the stack.
  • It throws an InvalidOperationException if the stack is empty.
Removing the top element from a stack using the Pop() method

Code

In the following code, we create a stack of strings.

First, we call the Push() method with the Lion, Tiger, and Panther strings. This inserts all three strings onto the stack, with Panther at the top of the stack.

We then show all the elements of the stack, and we can see that the stack has Panther at the top, followed by Tiger and Lion.

We now call the Pop() method and save the returned value in a local variable. Pop() removes and returns the Panther element present at the top of the stack since the stack is a LIFOLast In First Out data structure.

Then, we again display all of the elements of the stack and can observe that now, Tiger is at the top of the stack and Panther is removed.

using System;
using System.Collections.Generic;

class StackPop
{
    static void Main()
    {
        Stack<string> stack = new Stack<string>();
        stack.Push("Lion");
        stack.Push("Tiger");     
        stack.Push("Panther");
        Console.WriteLine("Current stack items: \n{0}\n", string.Join(",", stack.ToArray()));
        string item = stack.Pop();
        Console.WriteLine($"Removed {item} from the top of the stack.\n");       
        Console.WriteLine("Stack items:\n{0}", string.Join(",", stack.ToArray()));

    }
}

RELATED TAGS

c#
pop
communitycreator
RELATED COURSES

View all Courses

Keep Exploring