0
0
CppHow-ToBeginner · 3 min read

How to Implement Stack in C++: Simple Guide with Example

To implement a stack in C++, create a class with an array (or vector) to store elements and methods like push, pop, and top to manage the stack. Use a variable to track the current top position and update it as you add or remove items.
📐

Syntax

A basic stack class in C++ uses an array to hold elements and an integer to track the top position. It includes methods:

  • push(): adds an element on top
  • pop(): removes the top element
  • top(): returns the top element without removing it
  • isEmpty(): checks if the stack is empty
cpp
class Stack {
private:
    int arr[100]; // fixed size array
    int topIndex; // tracks the top element index
public:
    Stack() { topIndex = -1; } // constructor initializes empty stack
    void push(int x);
    void pop();
    int top();
    bool isEmpty();
};
💻

Example

This example shows a full stack implementation with push, pop, top, and isEmpty methods. It demonstrates adding and removing elements and printing the top value.

cpp
#include <iostream>
using namespace std;

class Stack {
private:
    int arr[100];
    int topIndex;
public:
    Stack() { topIndex = -1; }
    void push(int x) {
        if (topIndex < 99) {
            arr[++topIndex] = x;
        } else {
            cout << "Stack overflow\n";
        }
    }
    void pop() {
        if (topIndex >= 0) {
            topIndex--;
        } else {
            cout << "Stack underflow\n";
        }
    }
    int top() {
        if (topIndex >= 0) {
            return arr[topIndex];
        } else {
            cout << "Stack is empty\n";
            return -1; // error value
        }
    }
    bool isEmpty() {
        return topIndex == -1;
    }
};

int main() {
    Stack s;
    s.push(10);
    s.push(20);
    cout << "Top element: " << s.top() << "\n"; // 20
    s.pop();
    cout << "Top element after pop: " << s.top() << "\n"; // 10
    s.pop();
    cout << "Is stack empty? " << (s.isEmpty() ? "Yes" : "No") << "\n"; // Yes
    return 0;
}
Output
Top element: 20 Top element after pop: 10 Is stack empty? Yes
⚠️

Common Pitfalls

Common mistakes when implementing a stack include:

  • Not checking for stack overflow before pushing, which can cause writing outside the array.
  • Not checking for stack underflow before popping or accessing the top element, leading to errors.
  • Using incorrect index updates, like forgetting to increment or decrement the top index.

Always validate the stack state before operations.

cpp
/* Wrong way: No overflow check */
void push(int x) {
    arr[++topIndex] = x; // can overflow if topIndex >= 99
}

/* Right way: Check overflow */
void push(int x) {
    if (topIndex < 99) {
        arr[++topIndex] = x;
    } else {
        cout << "Stack overflow\n";
    }
}
📊

Quick Reference

Stack operations summary:

OperationDescription
push(x)Add element x to the top of the stack
pop()Remove the top element from the stack
top()Return the top element without removing it
isEmpty()Check if the stack has no elements

Key Takeaways

Use an array and an integer index to track the top of the stack.
Always check for overflow before pushing and underflow before popping.
Implement push, pop, top, and isEmpty methods for basic stack functionality.
Initialize the top index to -1 to represent an empty stack.
Return error or handle empty stack cases gracefully in top and pop methods.