edubun 한국어

Stacks

Checking that the brackets in {[()()]} pair up correctly takes one stack and 8 pushes and pops, one for each bracket.

Last in, first out

Think of a pile of plates. You put a clean plate on top, and when you need one you take it from the top. The plate you added last is the first one out. A stack is a data structure with exactly that rule, called last in, first out (LIFO). It offers two main operations: push puts a value on top, and pop removes the value on top and gives it back. Many stacks also offer peek, which looks at the top without removing it.

In MIT's 6.006 notes the stack is a special case of the sequence interface: insert last(x) and delete last(). That already tells you how to build one. Put the values in a dynamic array and treat the end of the array as the top. In the last unit the end was the cheap end, so push and pop each cost 1 step (amortized, because of the occasional copy). The size of the stack makes no difference. Popping from a stack of 3 values or of 3 million values is the same single step.

const stack = [];
stack.push(4);
stack.push(8);
stack.push(5);
console.log(stack.pop());           // 5, the last one pushed
console.log(stack[stack.length - 1]); // peek: 8
console.log(stack.length);          // 2
Loading

Drag to turn. Scroll or pinch to zoom.

A stack drawn as a pile. Push and pop work only at the top. Choose a bracket string and press Check brackets to watch a stack decide whether it is balanced.

Checking brackets

A classic use for a stack is checking that brackets are balanced, which every code editor and compiler does. Read the text from left to right. Each opening bracket, (, [ or {, is pushed. Each closing bracket must match the opener on top of the stack: if it does, pop that opener; if the stack is empty or the top is a different kind, the string is not balanced. At the end the stack must be empty, or some opener was never closed.

Try the strings in the lab. {[()()]} needs 4 pushes and 4 pops, 8 steps, and ends with an empty stack. ([)] fails at the third character: the ) arrives while [ is on top. (() reads to the end with one ( left over. Why does a stack fit this job? Brackets nest, and the most recently opened one must be the first to close. That is last in, first out.

Where else stacks appear

  • The call stack. When function a calls b and b calls c, the computer pushes a record for each call. When c returns, its record is popped and b continues where it stopped. Infinite recursion fills this stack, which is the "stack overflow" error.
  • Undo. An editor pushes each change. Undo pops the most recent change and reverses it.
  • Back button. A browser pushes each page you leave; Back pops the last one.
  • Depth-first search. The algorithms course used a stack to go as deep as possible in a maze before backing up.
BackgroundThe stack as a computing idea is usually traced to Friedrich L. Bauer and Klaus Samelson in Munich. Working on how to translate arithmetic formulas, they kept postponed operations in a store where the last item put in is the first taken out, and they called it the Keller, German for cellar. They applied for a patent on the method in 1957; it was granted in the United States in 1962. At about the same time, list processing by Allen Newell, Cliff Shaw and Herbert Simon at the RAND Corporation also relied on stacks, because their programs were full of recursion.
  1. A stack gives back values in which order?
    • First in, first out
    • Last in, first out
    • Smallest first
    • Random order
  2. Start empty. Push 4, push 8, push 5, pop, push 2. What is on top?
    • 4
    • 8
    • 5
    • 2
  3. After those operations, how many values are on the stack?
  4. Push A, then B, then C, then pop until empty. Put the popped values in order.
  5. How many pushes and pops in total does checking {[()()]} with the bracket method take?
  6. Checking ([)] from the left, where does it fail?
    • At the first (
    • At [
    • At )
    • At the final ]
  7. What is wrong with (() ?
    • A closer arrives on an empty stack
    • One ( is still on the stack at the end
    • Square brackets are missing
    • Nothing; it is balanced
  8. Popping from a stack (stored in a dynamic array) that holds 1,000 values takes how many steps?
  9. Function main calls draw, and draw calls line. While line runs, which record is on top of the call stack?
    • main
    • draw
    • line
    • none
  10. In which year did Bauer and Samelson apply for their patent on the stack method?
    • 1946
    • 1957
    • 1962
    • 1972
Key points
  • A stack is last in, first out: push on top, pop from the top.
  • Built on the end of a dynamic array, push and pop are 1 step each.
  • Bracket checking pushes openers and pops on each closer; {[()()]} takes 8 steps.
  • The call stack, undo and the Back button are stacks.
Sources for this course (5)
  • MIT OpenCourseWare 6.006 Introduction to Algorithms, Spring 2020 (Demaine, Ku, Solomon), lecture notes 2 Data Structures (interface vs data structure, Sequence and Set interfaces, stack = insert_last/delete_last, queue = insert_last/delete_first, array, linked list, dynamic array, amortized Θ(1) append), 4 Hashing (chaining, pigeonhole collisions, chain length n/m), 6 Binary Trees Part 1 (height, traversal order, O(h) operations) and 7 Binary Trees Part 2: AVL (Adelson-Velsky and Landis, 1962) at ocw.mit.edu/courses/6-006-introduction-to-algorithms-spring-2020/pages/lecture-notes
  • MDN Web Docs, Array.prototype.shift (shifts all values left by 1), Array.prototype.unshift, Map (insertion order, Map vs Object, spec requires sublinear average access) and Set (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects)
  • ECMAScript 2025 Language Specification (tc39.es/ecma262), 24.1 Map Objects and 24.2 Set Objects ("must be implemented using either hash tables or other mechanisms that, on average, provide access times that are sublinear on the number of elements"), Array.prototype.shift steps (Repeat, while k < len: move element k to k - 1)
  • D. E. Knuth, The Art of Computer Programming vol. 3 (2nd ed. 1998) section 6.4 History (H. P. Luhn, IBM internal memorandum January 1953, hashing with chaining; digit pairs added mod 10, 31415926 -> 4548) via gwern.net copy, and IEEE Spectrum, "Hans Peter Luhn and the Birth of the Hashing Algorithm" (2018)
  • "A brief history of the stack", SIGCIS (sigcis.org/files/A brief history.pdf: Bauer and Samelson applied for the patent in 1957, US 3,047,228 granted July 31, 1962; IPL list processing by Newell, Simon and Shaw at RAND 1956) and Wikipedia, Information Processing Language (Newell, Shaw, Simon, RAND and Carnegie Institute of Technology, about 1956).

Checked: 2026-10-18