Stacks are linear data structures that follow the Last In, First Out (LIFO) principle, where the last element added is the first one to be removed. They are widely used in programming for tasks that require sequential processing, such as expression evaluation, function call management (call stack), and backtracking algorithms. Here’s an overview of stacks in C++:
C++ provides a built-in stack container in the <stack>
header, which implements all necessary functionalities efficiently.
#include#include int main() { std::stack s; // Push elements onto the stack s.push(10); s.push(20); s.push(30); // Pop elements from the stack and print them while (!s.empty()) { std::cout << s.top() << " "; s.pop(); } std::cout << std::endl; return 0; }
If you want to understand how stacks work internally, here’s a basic implementation using an array:
#includeconst int MAX_SIZE = 100; class Stack { private: int top; int data[MAX_SIZE]; public: Stack() : top(-1) {} bool isEmpty() { return top == -1; } bool isFull() { return top == MAX_SIZE - 1; } void push(int val) { if (isFull()) { std::cout << "Stack overflow" << std::endl; return; } data[++top] = val; } void pop() { if (isEmpty()) { std::cout << "Stack underflow" << std::endl; return; } --top; } int peek() { if (isEmpty()) { std::cout << "Stack is empty" << std::endl; return -1; } return data[top]; } }; int main() { Stack s; s.push(10); s.push(20); s.push(30); std::cout << "Top element: " << s.peek() << std::endl; s.pop(); std::cout << "Top element after pop: " << s.peek() << std::endl; return 0; }