#include <iostream> #include <stack> int main() { std::stack<int> s; std::cout << (s.empty() ? "Empty" : "Not Empty") << std::endl; s.push(10); std::cout << (s.empty() ? "Empty" : "Not Empty") << std::endl; s.pop(); std::cout << (s.empty() ? "Empty" : "Not Empty") << std::endl; return 0; }
The stack starts empty, so s.empty() returns true and prints "Empty". After pushing 10, the stack is not empty, so it prints "Not Empty". After popping, the stack is empty again, so it prints "Empty".
#include <iostream> #define MAX 3 class Stack { int arr[MAX]; int top; public: Stack() { top = -1; } bool isFull() { return top == MAX - 1; } void push(int x) { if (!isFull()) { arr[++top] = x; } } void printStatus() { std::cout << (isFull() ? "Full" : "Not Full") << std::endl; } }; int main() { Stack s; s.push(1); s.push(2); s.push(3); s.printStatus(); return 0; }
The stack has a maximum size of 3. After pushing 3 elements, the top index reaches 2 (MAX-1), so isFull() returns true and prints "Full".
#include <iostream> #include <stack> int main() { std::stack<int> s; if (s.empty) { std::cout << "Stack is empty" << std::endl; } else { std::cout << "Stack is not empty" << std::endl; } return 0; }
The empty method is a function and must be called with parentheses (). Using s.empty without parentheses causes a compilation error.
#include <iostream> #define MAX 3 class Stack { int arr[MAX]; int top; public: Stack() { top = -1; } bool isFull() { return top == MAX - 1; } void push(int x) { if (!isFull()) { arr[++top] = x; } } void printStatus() { std::cout << (isFull() ? "Full" : "Not Full") << std::endl; } }; int main() { Stack s; s.push(5); s.push(10); s.printStatus(); return 0; }
The stack size is 3. After pushing two elements, the top index is 1, which is less than MAX-1 (2), so isFull() returns false and prints "Not Full".
Step-by-step:
push(1) → size 1
push(2) → size 2
pop() → size 1
push(3) → size 2
push(4) → size 3
push(5) → size 4 (max size reached)
pop() → size 3
Final size is 3.
