💻 Programming

Stack

Stack

A LIFO (Last-In-First-Out) data structure. Data inserted last leaves first. Used in function call stacks, undo, DFS, and more.

📖 Detailed Explanation

A Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle. Like stacking plates, the most recently added data is removed first. Data is inserted (push) and deleted (pop) only at the top. This contrasts with a Queue, which is a FIFO (First-In-First-Out) structure. The term stack comes from the meaning "to pile up," and it is one of the most basic yet powerful data structures.

All of a stack's core operations have O(1) constant time complexity. push (insert) adds an element to the top, and pop (delete) removes the top element and returns it. peek/top only looks at the top element without removing it. isEmpty (checks whether it is empty) and size (returns the size) are also O(1). A stack can be implemented with an array or a linked list; the array implementation has good cache efficiency because memory is contiguous, while the linked list implementation allows free dynamic resizing.

In computer science, the stack is used at the core of two important areas. The Call Stack pushes a stack frame (local variables, return address, etc.) on each function call to manage the flow of function execution. When a function ends, the frame is popped and control returns to the caller. The memory stack is the memory region that stores local variables and function parameters while a program runs. Unlike the Heap, it is allocated and freed automatically, so it is fast but limited in size. When recursive calls go deep, the stack memory fills up and a Stack Overflow occurs.

In practice, the stack is used at the core of many fields. The Undo feature pushes actions onto a stack and pops them on Ctrl+Z to restore the previous state. Bracket checking pushes opening brackets and pops when a closing bracket appears to check that they match. DFS (depth-first search) uses a stack to traverse graphs/trees. Stacks are also essential for browser back/forward, evaluating postfix expressions, reversing strings, and converting recursive functions to loops.

📊 Types of stacks and their uses

Call Stack

Manages function calls. Stores local variables, parameters, and return addresses in stack frames. The core of recursion and nested function calls.

Expression stack

Used for evaluating expressions. Used to convert infix to postfix and to evaluate postfix notation.

Memory stack

Stores local variables while a program runs. Faster than the heap but limited in size. Automatic memory management.

Undo stack

Stores the action history. Implements undo/redo. Essential in editors and graphics tools.

⏱️ Time complexity

Operation Time complexity Description
push (insert) O(1) Add an element to the top
pop (delete) O(1) Remove and return the element at the top
peek / top O(1) Check the top element (without removing it)
isEmpty O(1) Check whether it is empty
size O(1) Return the number of elements
Search O(n) Find a specific element (sequential search)

💻 Code Example

# Python 스택 구현 예제
from typing import Any, List, Optional


class Stack:
    """리스트 기반 스택 구현"""
    def __init__(self):
        self._items: List[Any] = []

    def push(self, item: Any) -> None:
        """스택의 top에 요소 추가 - O(1)"""
        self._items.append(item)

    def pop(self) -> Any:
        """스택의 top에서 요소 제거 및 반환 - O(1)"""
        if self.is_empty():
            raise IndexError("빈 스택에서 pop 시도")
        return self._items.pop()

    def peek(self) -> Any:
        """top 요소 확인 (제거 없음) - O(1)"""
        if self.is_empty():
            raise IndexError("빈 스택에서 peek 시도")
        return self._items[-1]

    def is_empty(self) -> bool:
        """스택이 비어있는지 확인 - O(1)"""
        return len(self._items) == 0

    def size(self) -> int:
        """스택의 크기 반환 - O(1)"""
        return len(self._items)

    def __len__(self) -> int:
        return self.size()

    def __repr__(self) -> str:
        return f"Stack({self._items})"


# 사용 예제
if __name__ == "__main__":
    stack = Stack()
    stack.push("A")
    stack.push("B")
    stack.push("C")

    print(f"스택: {stack}")           # Stack(['A', 'B', 'C'])
    print(f"top: {stack.peek()}")     # C
    print(f"크기: {len(stack)}")       # 3

    print(f"pop: {stack.pop()}")      # C
    print(f"pop: {stack.pop()}")      # B
    print(f"남은 스택: {stack}")        # Stack(['A'])


# ========== 실무 활용 예제 ==========

# 1. 괄호 유효성 검사
def is_valid_parentheses(s: str) -> bool:
    """괄호가 올바르게 짝지어졌는지 확인"""
    stack = []
    pairs = {')': '(', '}': '{', ']': '['}

    for char in s:
        if char in '({[':
            stack.append(char)
        elif char in ')}]':
            if not stack or stack[-1] != pairs[char]:
                return False
            stack.pop()

    return len(stack) == 0

print(is_valid_parentheses("({[]})"))  # True
print(is_valid_parentheses("([)]"))    # False


# 2. 문자열 뒤집기
def reverse_string(s: str) -> str:
    """스택을 사용해 문자열 뒤집기"""
    stack = list(s)
    result = []
    while stack:
        result.append(stack.pop())
    return ''.join(result)

print(reverse_string("Hello"))  # olleH


# 3. DFS (깊이 우선 탐색) - 스택 활용
def dfs_iterative(graph: dict, start: str) -> List[str]:
    """스택을 사용한 반복적 DFS"""
    visited = set()
    stack = [start]
    result = []

    while stack:
        node = stack.pop()
        if node not in visited:
            visited.add(node)
            result.append(node)
            # 역순으로 추가 (왼쪽 자식 먼저 방문하도록)
            for neighbor in reversed(graph.get(node, [])):
                if neighbor not in visited:
                    stack.append(neighbor)

    return result

graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}
print(f"DFS 순회: {dfs_iterative(graph, 'A')}")  # ['A', 'B', 'D', 'E', 'F', 'C']


# 4. 실행 취소 (Undo) 시스템
class UndoSystem:
    """간단한 Undo/Redo 시스템"""
    def __init__(self):
        self.undo_stack = []
        self.redo_stack = []
        self.current_state = ""

    def execute(self, action: str):
        """작업 실행"""
        self.undo_stack.append(self.current_state)
        self.current_state = action
        self.redo_stack.clear()  # 새 작업 시 redo 스택 초기화
        print(f"실행: {action}")

    def undo(self) -> Optional[str]:
        """실행 취소"""
        if not self.undo_stack:
            print("더 이상 취소할 수 없습니다.")
            return None
        self.redo_stack.append(self.current_state)
        self.current_state = self.undo_stack.pop()
        print(f"취소 -> 현재 상태: {self.current_state or '(초기 상태)'}")
        return self.current_state

    def redo(self) -> Optional[str]:
        """다시 실행"""
        if not self.redo_stack:
            print("다시 실행할 작업이 없습니다.")
            return None
        self.undo_stack.append(self.current_state)
        self.current_state = self.redo_stack.pop()
        print(f"다시 실행 -> 현재 상태: {self.current_state}")
        return self.current_state

editor = UndoSystem()
editor.execute("Hello")
editor.execute("Hello World")
editor.execute("Hello World!")
editor.undo()  # Hello World
editor.undo()  # Hello
editor.redo()  # Hello World
// JavaScript 스택 구현 예제

class Stack {
    constructor() {
        this.items = [];
    }

    // 스택의 top에 요소 추가 - O(1)
    push(item) {
        this.items.push(item);
        return this;  // 메서드 체이닝 지원
    }

    // 스택의 top에서 요소 제거 및 반환 - O(1)
    pop() {
        if (this.isEmpty()) {
            throw new Error("빈 스택에서 pop 시도");
        }
        return this.items.pop();
    }

    // top 요소 확인 (제거 없음) - O(1)
    peek() {
        if (this.isEmpty()) {
            throw new Error("빈 스택에서 peek 시도");
        }
        return this.items[this.items.length - 1];
    }

    // 스택이 비어있는지 확인 - O(1)
    isEmpty() {
        return this.items.length === 0;
    }

    // 스택의 크기 - O(1)
    get size() {
        return this.items.length;
    }

    // 스택 초기화
    clear() {
        this.items = [];
    }

    // 배열로 변환
    toArray() {
        return [...this.items];
    }

    toString() {
        return `Stack([${this.items.join(', ')}])`;
    }
}


// 사용 예제
const stack = new Stack();
stack.push("A").push("B").push("C");

console.log(`스택: ${stack}`);            // Stack([A, B, C])
console.log(`top: ${stack.peek()}`);      // C
console.log(`크기: ${stack.size}`);        // 3

console.log(`pop: ${stack.pop()}`);       // C
console.log(`pop: ${stack.pop()}`);       // B
console.log(`남은 스택: ${stack}`);         // Stack([A])


// ========== 실무 활용 예제 ==========

// 1. 괄호 유효성 검사
function isValidParentheses(s) {
    const stack = [];
    const pairs = { ')': '(', '}': '{', ']': '[' };

    for (const char of s) {
        if ('({['.includes(char)) {
            stack.push(char);
        } else if (')}]'.includes(char)) {
            if (stack.length === 0 || stack[stack.length - 1] !== pairs[char]) {
                return false;
            }
            stack.pop();
        }
    }

    return stack.length === 0;
}

console.log(isValidParentheses("({[]})")); // true
console.log(isValidParentheses("([)]"));   // false


// 2. 브라우저 히스토리 (뒤로가기/앞으로가기)
class BrowserHistory {
    constructor(homepage) {
        this.backStack = [];
        this.forwardStack = [];
        this.current = homepage;
    }

    visit(url) {
        this.backStack.push(this.current);
        this.current = url;
        this.forwardStack = [];  // 새 페이지 방문 시 앞으로 가기 스택 초기화
        console.log(`방문: ${url}`);
    }

    back() {
        if (this.backStack.length === 0) {
            console.log("뒤로 갈 수 없습니다.");
            return this.current;
        }
        this.forwardStack.push(this.current);
        this.current = this.backStack.pop();
        console.log(`뒤로 -> ${this.current}`);
        return this.current;
    }

    forward() {
        if (this.forwardStack.length === 0) {
            console.log("앞으로 갈 수 없습니다.");
            return this.current;
        }
        this.backStack.push(this.current);
        this.current = this.forwardStack.pop();
        console.log(`앞으로 -> ${this.current}`);
        return this.current;
    }
}

const browser = new BrowserHistory("google.com");
browser.visit("youtube.com");
browser.visit("facebook.com");
browser.back();    // youtube.com
browser.back();    // google.com
browser.forward(); // youtube.com


// 3. DFS (깊이 우선 탐색) - 스택 활용
function dfsIterative(graph, start) {
    const visited = new Set();
    const stack = [start];
    const result = [];

    while (stack.length > 0) {
        const node = stack.pop();
        if (!visited.has(node)) {
            visited.add(node);
            result.push(node);
            // 역순으로 추가
            const neighbors = graph[node] || [];
            for (let i = neighbors.length - 1; i >= 0; i--) {
                if (!visited.has(neighbors[i])) {
                    stack.push(neighbors[i]);
                }
            }
        }
    }

    return result;
}

const graph = {
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
};
console.log(`DFS 순회: ${dfsIterative(graph, 'A')}`); // A,B,D,E,F,C


// 4. 수식 계산기 (후위 표기법)
function evaluatePostfix(expression) {
    const stack = [];
    const tokens = expression.split(' ');

    for (const token of tokens) {
        if (!isNaN(token)) {
            stack.push(parseFloat(token));
        } else {
            const b = stack.pop();
            const a = stack.pop();
            switch (token) {
                case '+': stack.push(a + b); break;
                case '-': stack.push(a - b); break;
                case '*': stack.push(a * b); break;
                case '/': stack.push(a / b); break;
            }
        }
    }

    return stack.pop();
}

// "3 + 4 * 2" -> 후위: "3 4 2 * +"
console.log(evaluatePostfix("3 4 2 * +"));  // 11
// "( 5 - 3 ) * 4" -> 후위: "5 3 - 4 *"
console.log(evaluatePostfix("5 3 - 4 *"));  // 8


// 5. Min Stack (최솟값 O(1) 조회 스택)
class MinStack {
    constructor() {
        this.stack = [];
        this.minStack = [];  // 각 시점의 최솟값 저장
    }

    push(val) {
        this.stack.push(val);
        const minVal = this.minStack.length === 0
            ? val
            : Math.min(val, this.minStack[this.minStack.length - 1]);
        this.minStack.push(minVal);
    }

    pop() {
        this.stack.pop();
        this.minStack.pop();
    }

    top() {
        return this.stack[this.stack.length - 1];
    }

    getMin() {
        return this.minStack[this.minStack.length - 1];
    }
}

const minStack = new MinStack();
minStack.push(5);
minStack.push(2);
minStack.push(7);
console.log(`최솟값: ${minStack.getMin()}`);  // 2
minStack.pop();
minStack.pop();
console.log(`최솟값: ${minStack.getMin()}`);  // 5

🗣️ Examples of Practical Conversations

In a technical interview - Stack vs Queue comparison

"The key difference between a stack and a queue is the order in which data is processed. A stack is LIFO, so the last item in comes out first, which suits the function call stack and Undo. A queue is FIFO, so the first item in comes out first, which is used for job queues and BFS traversal. For example, browser back goes back starting from the most recent page, so it uses a stack, while a web server must process requests in the order they arrive, so it uses a queue. In time complexity, both are the same at O(1) for insert/delete."

While debugging - fixing a Stack Overflow

"A Stack Overflow error occurs because the recursive function's base case is missing or the recursion is so deep that the call stack fills up. There are three ways to fix it. First, check that the base case is defined correctly. Second, convert the recursion to a loop and use an explicit stack. Third, if the language supports tail call optimization, rewrite it in tail-recursive form. In Python you can raise the limit with sys.setrecursionlimit(), but that is not a fundamental solution."

During a code review - recursion vs loops

"This DFS function is implemented with recursion, but if the graph depth is unpredictable, it's safer to switch to a stack. Recursion makes the code cleaner, but each call pushes a frame onto the call stack, so it can blow up if the depth exceeds a few thousand. Using an explicit stack uses heap memory, so you can traverse much deeper. Also, when you need memoization, an explicit stack is easier to manage."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

1
Stack Overflow

The size of the call stack is limited. If recursive calls go too deep or fall into infinite recursion, the stack fills up and the program halts. In JavaScript the limit varies by browser but is in the thousands to tens of thousands of calls, and in Python the default limit is 1000. When the depth is unpredictable or large, use an explicit stack and a loop instead of recursion.

2
Recursion depth limit

Many languages limit recursion depth. In Python you can check it with sys.getrecursionlimit() and change it with sys.setrecursionlimit(), but exceeding the system stack size still crashes. In languages that support tail call optimization (TCO), such as Scheme and Scala, writing the code in tail-recursive form reuses stack frames and solves this problem.

3
Memory management and stack vs heap

Stack memory is allocated and freed automatically, so it is fast but small (usually 1-8MB). Allocate large data on the heap. Declaring a large array as a local variable can cause a stack overflow. Also be careful: if a reference to a value stored on the stack remains after the function returns, it can cause a dangling pointer problem.

🔗 Related Terms

📚 Learn More