Home

Stack Data Structure

What is a Stack?

A stack is a linear data structure that follows the Last In, First Out (LIFO) principle. Elements are added and removed from the same end called the top of the stack. It is similar to a stack of plates where you can only take the top plate off or put a new plate on top.

Real-World Analogy

Think of a stack as a stack of plates. You can only add or remove plates from the top of the stack, making it a good example of the LIFO principle.

Example

Imagine a stack with elements 1, 2, and 3. The stack looks like this:

3
2
1

Code Snippets

C++

#include <iostream>
#include <stack>

int main() {
    std::stack<int> s;
    s.push(1);
    s.push(2);
    s.push(3);
    
    while (!s.empty()) {
        std::cout << s.top() << std::endl;
        s.pop();
    }
    
    return 0;
}

Java

import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        
        while (!stack.isEmpty()) {
            System.out.println(stack.peek());
            stack.pop();
        }
    }
}

Python

stack = []

# Push elements
stack.append(1)
stack.append(2)
stack.append(3)

# Pop elements
while stack:
    print(stack.pop())

C

#include <stdio.h>
#include <stdlib.h>

#define MAX 100

typedef struct {
    int top;
    int items[MAX];
} Stack;

voi