Clear a Stack in C++
To clear all elements from a stack in C++, we can use the std::stack::pop() function in the while loop till the stack becomes empty. When the stack empty condition is satisfied, it indicates that all the elements from a stack are cleared.
C++ Program to Clear a Stack
// C++ Program to illustrate how to clear all elements from
// a stack
#include <iostream>
#include <stack>
using namespace std;
// Driver Code
int main()
{
// Creating a stack of elements
stack<int> stackData;
// Adding elements to the stack
stackData.push(10);
stackData.push(20);
stackData.push(30);
stackData.push(40);
// Printing the original stack
cout << "Original Stack: ";
while (!stackData.empty()) {
cout << stackData.top() << " ";
stackData.pop();
}
cout << endl;
// Clearing all elements from the stack
cout << "After clearing - Updated Stack: ";
while (!stackData.empty()) {
stackData.pop();
}
// Printing the updated stack. Empty
cout << "[Empty]" << endl;
return 0;
}
Output
Original Stack: 40 30 20 10 After clearing - Updated Stack: [Empty]
Time Complexity: O(N), where N is the number of elements.
Auxiliary Space: O(1)
How to Clear a Stack in C++?
In C++, stacks are a type of container adaptor with a LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. In this article, we will learn to clear all the elements from a stack in C++.
Example:
Input:
myStack = 40, 30, 20, 10
Output:
After clearing - Updated Stack: [Empty]
Contact Us