How to Check if a Stack is Empty in C++?
In C++, we have a stack data structure that follows a LIFO (Last In First Out) rule of operation. In this article, we will learn how to check if a stack is empty in C++.
Example:
Input:
myStack = {1, 2, 3 } Output:
Stack is not Empty
Checking if a Stack is Empty in C++
To check if a stack is empty in C++, we can use the std::stack::empty() function that returns a boolean value true if the stack is empty and false if the stack is not empty.
C++ Program to Check if a Stack is Empty
The below example demonstrates how we can check if a given stack is empty or not in C++ STL.
// C++ program to illustrate how to check if a stack is
// empty
#include <iostream>
#include <stack>
using namespace std;
int main()
{
// Creating a stack
stack<int> mystack;
// Checking if stack is empty
if (mystack.empty())
cout << "Stack is empty\n";
else
cout << "Stack is not empty\n";
// Adding elements to the stack
mystack.push(10);
mystack.push(20);
mystack.push(30);
// Again Checking if stack is empty
if (mystack.empty())
cout << "After Updation Stack is empty\n";
else
cout << "After Updation Stack is not empty\n";
return 0;
}
Output
Stack is empty After Updation Stack is not empty
Time Complexity: O(1)
Auxiliary Space: O(1)