💻 Programming

Stack

Stack

A LIFO (last-in, first-out) data structure. Used in function calls and recursion. Also refers to a tech stack.

📖 Detailed Explanation

A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. The element added last is removed first, the same principle as stacking plates. It is a simple but powerful structure in which push adds an element and pop removes one.

In programming, stacks are central to managing function calls. When a function is called, its return address, parameters, and local variables are pushed onto the call stack, and popped when the function ends. This is also why a stack overflow occurs when a recursive function goes too deep. Each thread has its own independent call stack.

Stacks are used in a variety of algorithms. Typical examples include bracket matching checks, converting expressions to postfix notation, depth-first search (DFS), and Undo functionality. The browser's back button is also implemented by managing the visit history as a stack.

A tech stack is used in a different sense. In web development, it refers to a combination of technologies used for software development, such as LAMP (Linux, Apache, MySQL, PHP) or MERN (MongoDB, Express, React, Node.js). It covers the technology choices at each layer, including frontend, backend, and database.

💻 Code Example

// 스택 자료구조 구현 및 활용 예제

// JavaScript 스택 구현
class Stack {
    constructor() {
        this.items = [];
    }

    push(element) {
        this.items.push(element);
    }

    pop() {
        if (this.isEmpty()) return null;
        return this.items.pop();
    }

    peek() {
        if (this.isEmpty()) return null;
        return this.items[this.items.length - 1];
    }

    isEmpty() {
        return this.items.length === 0;
    }

    size() {
        return this.items.length;
    }
}

// 스택 사용 예시
const stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
console.log(stack.pop());   // 30
console.log(stack.peek());  // 20

// 괄호 매칭 검사 (스택 활용)
function isBalanced(str) {
    const stack = [];
    const pairs = { ')': '(', ']': '[', '}': '{' };

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

console.log(isBalanced('({[]})')); // true
console.log(isBalanced('([)]'));   // false

🗣️ Examples of Practical Conversations

PM: "How should we decide the tech stack for the new project?"

Tech lead: "We need to consider the requirements and the team's skills. There are a lot of real-time features, so Node.js with Socket.io and React for the frontend seem like a good fit."

Backend developer: "I suggest PostgreSQL for the database, since we'll have a lot of complex relational queries."

Tech lead: "Sounds good. Let's go with the PERN stack (PostgreSQL, Express, React, Node.js)."

Interviewer: "Explain the difference between a stack and a queue and when each is used."

Candidate: "A stack is LIFO, so the last element comes out first, while a queue is FIFO, so the first element comes out first. Stacks are used for function calls, Undo, and DFS, and queues are used for job queues, BFS, and event handling."

Interviewer: "When does a stack overflow occur?"

Candidate: "It occurs when a recursive function has no termination condition or is too deep, so the call stack exceeds its limit. To prevent it, convert to a loop or use tail recursion optimization."

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

Reviewer: "This recursive function could cause a stack overflow with large input."

Author: "You're right. The depth is unpredictable, so it could be a problem."

Reviewer: "Converting it to a loop with an explicit stack is safer because it uses heap memory."

Author: "Good suggestion. I'll refactor it with a while loop and an array stack."

⚠️ Cautions

🔗 Related Terms

📚 Learn More