Writing a Stack in C++
2 min read

Writing a Stack in C++
A stack is a fundamental data structure that operates on the principle of Last In, First Out (LIFO). This means that the last element added to the stack is the first one to be removed. Stacks are widely used in programming for tasks like expression evaluation, backtracking, and function call management.
Core Operations
A stack typically supports the following operations:
- Push: Add an element to the top of the stack.
- Pop: Remove the top element from the stack.
- Peek/Top: View the top element without removing it.
- IsEmpty: Check if the stack is empty.
Implementation in C++
Here is an example of how you can implement a stack in C++ using arrays:
1#include <iostream>2#define MAX 100034class Stack {5private:6 int top;7 int arr[MAX]; // Array to store stack elements89public:10 Stack() { top = -1; } // Constructor to initialize stack1112 bool push(int x) {13 if (top >= (MAX - 1)) {14 std::cout << "Stack Overflow\n";15 return false;16 } else {17 arr[++top] = x;18 return true;19 }20 }2122 int pop() {23 if (top < 0) {24 std::cout << "Stack Underflow\n";25 return -1;26 } else {27 return arr[top--];28 }29 }3031 int peek() {32 if (top < 0) {33 std::cout << "Stack is Empty\n";34 return -1;35 } else {36 return arr[top];37 }38 }3940 bool isEmpty() {41 return (top < 0);42 }43};4445int main() {46 Stack s;47 s.push(10);48 s.push(20);49 s.push(30);50 std::cout << s.pop() << " popped from stack\n";51 std::cout << "Top element is " << s.peek() << "\n";52 return 0;53}
Advantages of Using Stacks
- Simplicity: Easy to implement and use.
- Efficiency: Operations like push and pop are performed in constant time, O(1).
- Versatility: Useful in various applications like undo mechanisms, parsing expressions, and more.
By implementing a stack in C++, you gain a deeper understanding of how this data structure works and its importance in computer science.