STACK: Intuition
A Stack is a linear data structure that follows the Last In, First Out (LIFO) principle:
Think of a stack of plates: you add plates on top and remove plates from the top.
Key Operations
Operation Description
push(x) Add element x to the top of the stack
pop() Remove and return the top element
peek() / top() View the top element without removing it
isEmpty() Check if the stack is empty
size() Return number of elements
Applications of Stack
1. Function call management (Call stack)
2. Undo/Redo operations
3. Expression evaluation ( infix → postfix )
4. Balanced parentheses check
5. Backtracking algorithms (maze, sudoku)
6. Web browser history
7. Language parsing and compilation
Implementation
Python (Using list)
class Stack:
def __init__(self):
[Link] = []
def push(self, val):
[Link](val)
def pop(self):
if self.is_empty():
return None
return [Link]()
def top(self):
if self.is_empty():
return None
return [Link][-1]
def is_empty(self):
return len([Link]) == 0
def size(self):
return len([Link])
Java
import [Link].*;
class StackDemo {
Stack<Integer> stack = new Stack<>();
void push(int val) {
[Link](val);
}
int pop() {
return [Link]();
}
int top() {
return [Link]();
}
boolean isEmpty() {
return [Link]();
}
int size() {
return [Link]();
}
}
C++
#include <iostream>
#include <stack>
using namespace std;
class StackDemo {
stack<int> s;
public:
void push(int val) {
[Link](val);
}
void pop() {
if (![Link]()) [Link]();
}
int top() {
return [Link]();
}
bool isEmpty() {
return [Link]();
}
int size() {
return [Link]();
}
};