How to Pop an Element From a Stack in C++?
Last Updated :
04 Mar, 2024
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++
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack< int > stackData;
stackData.push(10);
stackData.push(20);
stackData.push(30);
stackData.push(40);
cout << "Before Popping - Original Stack: " ;
stack< int > oStack = stackData;
while (!oStack.empty()) {
cout << oStack.top() << " " ;
oStack.pop();
}
cout << endl;
if (!stackData.empty()) {
stackData.pop();
}
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)
Share your thoughts in the comments
Please Login to comment...