Java

Stack & Queue

voider 2020. 9. 9. 10:45

๐Ÿ“š ์ž๋ฐ”์˜ ์ •์„์„ ์ •๋ฆฌํ•œ ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค.

์ถœ์ฒ˜ : https://gohighbrow.com/stacks-and-queues/

์Šคํƒ์€ ๋งˆ์ง€๋ง‰์— ์ €์žฅํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์žฅ ๋จผ์ € ๊บผ๋‚ด๋Š” Last in first out(LIFO)๊ตฌ์กฐ.
ํ๋Š” ์ฒ˜์Œ ์ €์žฅํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์žฅ ๋จผ์ € ๊บผ๋‚ด๋Š” First in first out(FIFO)๊ตฌ์กฐ๋‹ค.
์ฐธ๊ณ ๋กœ Stack์€ ํด๋ž˜์Šค, Queue๋Š” ์ธํ„ฐํŽ˜์ด์Šค๋‹ค.

Stack์˜ ๋ฉ”์„œ๋“œ

method ์„ค๋ช…
boolean empty() Stack์ด ๋น„์—ˆ๋Š”์ง€ ํ™•์ธ
Object peek() Stack ๋งจ ์œ„์— ์ €์žฅ๋œ ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ pop๊ณผ ๋‹ฌ๋ฆฌ ๊บผ๋‚ด๋Š” ๊ฒƒ์€ ์•„๋‹˜
๋น„์–ด ์žˆ๋‹ค๋ฉด EmptyStackException
Oject pop() ๋งจ ์œ„์— ์ €์žฅ๋œ ๊ฐ์ฒด๋ฅผ ๊บผ๋‚ธ๋‹ค. ๋น„์—ˆ๋‹ค๋ฉด ์—ญ์‹œ
EmptyStackExcption
Object push(Object item) Stack์— ๊ฐ์ฒด๋ฅผ ์ €์žฅํ•œ๋‹ค
int search(Object o) ์ฃผ์–ด์ง„ ๊ฐ์ฒดo๋ฅผ ์ฐพ์•„์„œ index๋ฅผ ๋ฐ˜ํ™˜
๋ฐฐ์—ด๊ณผ ๋‹ฌ๋ฆฌ 0์ด ์•„๋‹Œ 1๋ถ€ํ„ฐ ์‹œ์ž‘

Queue์˜ ๋ฉ”์„œ๋“œ

method ์„ค๋ช…
boolean add(Object o) ์ง€์ •ํ•œ ๊ฐ์ฒดo๋ฅผ Queue์— ์ถ”๊ฐ€.
์ €์žฅ ๊ณต๊ฐ„์ด ๋ถ€์กฑํ•˜๋ฉด IllegalStateException
Ojbect remove() ๊ฐ์ฒด๋ฅผ ๊บผ๋‚ด ๋ฐ˜ํ™˜. ๋น„์–ด ์žˆ์œผ๋ฉด NoSuchElementException
Object element() ์‚ญ์ œ ์—†์ด ์š”์†Œ๋ฅผ ์ฝ๋Š”๋‹ค. peek๊ณผ ๋‹ฌ๋ฆฌ ๋น„์—ˆ์„ ๋•Œ NoSuchElementException
boolean offer(Object o) ๊ฐ์ฒด ์ €์žฅ
Object poll() ๊ฐ์ฒด๋ฅผ ๊บผ๋‚ด ๋ฐ˜ํ™˜, ๋น„์—ˆ์œผ๋ฉด null
Object peek() ์‚ญ์ œ ์—†์ด ์š”์†Œ ์ฝ๋Š”๋‹ค. ๋น„์—ˆ์œผ๋ฉด null.

Stack vs. Queue

package com.javaex.ch11;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class StackAndQueue {
    public static void main(String[] args) {
        Stack stack = new Stack();
        Queue queue = new LinkedList(); //Queue์ธํ„ฐํŽ˜์ด์Šค ๊ตฌํ˜„์ฒด์ธ LinkedList

        stack.push("0");
        stack.push("1");
        stack.push("2");

        queue.offer("0");
        queue.offer("1");
        queue.offer("2");

        System.out.println("=========Stack=========");
        while (!stack.empty()) {
            System.out.println(stack.pop());
        }

        System.out.println("=========Queue=========");
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }
    }
}

/*๊ฒฐ๊ณผ
=========Stack=========
2
1
0
=========Queue=========
0
1
2
*/

Queue์˜ ๋ณ€ํ˜•

Dequeue

Stack๊ณผ Queue์˜ ๊ฒฐํ•ฉ. ์–‘๋์—์„œ ์ €์žฅoffer๊ณผ ์‚ญ์ œpoll๊ฐ€๋Šฅ.
๊ตฌํ˜„ ํด๋ž˜์Šค:ArrayDeque, LinkedList

PriorityQueue

์šฐ์„ ์ˆœ์œ„ ํ. ์šฐ์„ ์ˆœ์œ„๊ฐ€ ๋†’์€ ๊ฒƒ๋ถ€ํ„ฐ ๊บผ๋ƒ„
null์ €์žฅ ๋ถˆ๊ฐ€.
์ž…๋ ฅ 3,1,5,2,4 -> ์ถœ๋ ฅ 1,2,3,4,5

Blocking Queue

๋น„์–ด ์žˆ์„ ๋•Œ ๊บผ๋‚ด๊ธฐ์™€ ๊ฐ€๋“ ์ฐจ ์žˆ์„ ๋•Œ ๋„ฃ๊ธฐ๋ฅผ
์ง€์ •๋œ ์‹œ๊ฐ„๋™์•ˆ ์ง€์—ฐblock์‹œํ‚ด

'Java' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

Arrays  (0) 2020.09.09
List  (0) 2020.09.09
Collections Framework - ํ•ต์‹ฌ ์ธํ„ฐํŽ˜์ด์Šค  (0) 2020.09.09
๋‚ด๋ถ€ ํด๋ž˜์Šคinner class  (0) 2020.09.09
์ถ”์ƒํด๋ž˜์Šค & ์ธํ„ฐํŽ˜์ด์Šค  (0) 2020.09.09