Stack

stack

  • ๋‚˜์ค‘์— ๋“ค์–ด๊ฐ„ ๊ฒƒ์ด ๋จผ์ € ๋‚˜์˜ค๋Š” ๊ตฌ์กฐ

  • ์„ ์ž…ํ›„์ถœ, LIFO, last in first out

  • ์ž…๊ตฌ์™€ ์ถœ๊ตฌ๊ฐ€ ๋™์ผํ•œ ํ˜•ํƒœ๋กœ ์Šคํƒ์„ ์‹œ๊ฐํ™”

    • ์˜ˆ) ๋ฐ•์Šค์Œ“๊ธฐ, ์ ‘์‹œ์Œ“๊ธฐ ๋“ฑ

  • ์˜ˆ์‹œ

    • ๊ทธ๋ž˜ํ”„์˜ ๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰(DFS)์—์„œ ์‚ฌ์šฉํ•œ๋‹ค.

    • ์‹œ์Šคํ…œ ํ•ดํ‚น์—์„œ ๋ฒ„ํผ์˜ค๋ฒ„ํ”Œ๋กœ์šฐ ์ทจ์•ฝ์ ์„ ์ด์šฉํ•œ ๊ณต๊ฒฉ์„ ํ•  ๋•Œ, ์Šคํƒ ๋ฉ”๋ชจ๋ฆฌ์˜ ์˜์—ญ์—์„œ ํ•œ๋‹ค.

    • ์ปดํ“จํ„ฐ ์‚ฌ์น™์—ฐ์‚ฐ ๊ณ„์‚ฐ์—์„œ ํ›„์œ„ํ‘œ๊ธฐ๋ฒ•

    • ์ธํ„ฐ๋ŸฝํŠธ์ฒ˜๋ฆฌ, ์ˆ˜์‹์˜ ๊ณ„์‚ฐ, ์„œ๋ธŒ๋ฃจํ‹ด์˜ ๋ณต๊ท€ ๋ฒˆ์ง€ ์ €์žฅ ๋“ฑ์— ์“ฐ์ธ๋‹ค.

    • ๋ฐฑํŠธ๋ž˜ํ‚น, ์ธํ„ฐ๋„ท ์‚ฌ์šฉ๊ธฐ๋ก ๋ณด๊ด€

    • ๋ธŒ๋ผ์šฐ์ €์˜ ๋’ค๋กœ๊ฐ€๊ธฐ

    • ์‹คํ–‰์ทจ์†Œ

    • ์žฌ๊ท€ํ•จ์ˆ˜

    • ์—ญ์ˆœ๋ฌธ์ž์—ด - ๋ฌธ์ž์—ด ๊ฑฐ๊พธ๋กœ ๋’ค์ง‘๊ธฐ

  • ์žฅ๋‹จ์ 

    • top ๋ฅผ ํ†ตํ•ด ์ ‘๊ทผํ•ด์„œ ๋ฐ์ดํ„ฐ ์ ‘๊ทผ, ์‚ฝ์ž…, ์‚ญ์ œ๊ฐ€ ๋น ๋ฅด๋‹ค.

    • top ์œ„์น˜ ์ด์™ธ์˜ ๋ฐ์ดํ„ฐ์— ์ ‘๊ทผํ•  ์ˆ˜ ์—†๋‹ค. ๊ทธ๋ž˜์„œ ํƒ์ƒ‰์—๋Š” ๋ชจ๋“  ์š”์†Œ๋ฅผ ๊บผ๋‚ด์„œ ์ง„ํ–‰ํ•ด์•ผํ•œ๋‹ค.

  • ์‹œ๊ฐ„ ๋ณต์žก๋„

    • ์‚ฝ์ž…๊ณผ ์‚ญ์ œ : O(1)

    • ํƒ์ƒ‰ : O(n)

  • ๊ตฌํ˜„

    • java.util.Stack import ํ•˜๋ฉด ๋ฐ”๋กœ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•จ

  • ์ง€์› ๋งค์†Œ๋“œ

    • push : ์‚ฝ์ž…

    • peek : ์ตœ์ƒ๋‹จ ์›์†Œ ์ถœ๋ ฅ

    • isEmpty, empty : ์Šคํƒ์ด ๋น„์–ด์žˆ๋‹ค๋ฉด true, ์•„๋‹ˆ๋ฉด false

    • pop : ์‚ญ์ œ

์˜ˆ์‹œ

package practice.algorithm.stackqueue;

import java.util.Stack;

public class StackPractice {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();

        stack.push("h");
        stack.push("e");
        stack.push("l");
        stack.push("l");
        stack.push("o");
        System.out.println("stack = " + stack);

        System.out.println("stack.empty() = " + stack.empty());

        System.out.println("stack.peek() = " + stack.peek());
        System.out.println("stack = " + stack);

        System.out.println("stack.pop() = " + stack.pop());
        System.out.println("stack.pop() = " + stack.pop());
        System.out.println("stack = " + stack);

        while(!stack.empty()) {
            System.out.println("stack.pop() = " + stack.pop());
        }
        System.out.println("stack = " + stack);
        System.out.println("stack.isEmpty() = " + stack.isEmpty());
    }
    
    /*
    stack = [h, e, l, l, o]
    stack.empty() = false
    stack.peek() = o
    stack = [h, e, l, l, o]
    stack.pop() = o
    stack.pop() = l
    stack = [h, e, l]
    stack.pop() = l
    stack.pop() = e
    stack.pop() = h
    stack = []
    stack.isEmpty() = true
    */
}

Last updated