Horje
How to Pop an Element From a Stack in C++?

In C++, stacks are used to store a collection of similar types of data in a Last-In-First-Out (LIFO) manner. In this article, we will discuss how to pop an element from a stack in C++.

Example:

Input:
myStack = {10, 34, 12, 90, 1};

Output:
myStack = {10, 34, 12, 90};

Removing an Element from a Stack in C++

In STL, the std::stack::pop() function is used to remove the top element from the stack. However, it’s important to note that this function does not return the popped element. To access the top element before popping it, we can use the std::stack::top() function.

C++ Program to Pop an Element From a Stack

C++

// C++ Program to pop an element from a stack
#include <iostream>
#include <stack>
  
using namespace std;
  
int main()
{
    // Creating a stack with elements
    stack<int> stackData;
  
    // Pushing elements to the stack
    stackData.push(10);
    stackData.push(20);
    stackData.push(30);
    stackData.push(40);
  
    // Printing the original stack before popping
    cout << "Before Popping - Original Stack: ";
    stack<int> oStack = stackData;
    while (!oStack.empty()) {
        cout << oStack.top() << " ";
        oStack.pop();
    }
    cout << endl;
  
    // Popping an element from the stack
    if (!stackData.empty()) {
        stackData.pop();
    }
  
    // Printing the updated stack after popping
    cout << "After Popping - Updated Stack: ";
    while (!stackData.empty()) {
        cout << stackData.top() << " ";
        stackData.pop();
    }
    cout << endl;
  
    return 0;
}

Output

Before Popping - Original Stack: 40 30 20 10 
After Popping - Updated Stack: 30 20 10 

Time Complexity: O(1)
Auxiliary Space: O(1)




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Push an Element into Stack in C++? How to Push an Element into Stack in C++?
C++ Program to Count the Dupicate Elements in an Array C++ Program to Count the Dupicate Elements in an Array
How to Access the Top Element of a Stack in C++? How to Access the Top Element of a Stack in C++?
How to Copy a Stack in C++? How to Copy a Stack in C++?
How to Clear a Stack in C++? How to Clear a Stack in C++?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14