알고리즘&자료구조

Java로 큐, 스택 이용하기

한땀코딩 2020. 5. 31. 22:09

스택 & 큐

알고리즘과 자료구조를 공부하면서 스택과 큐라는 자료구조를 익히게 되었는데, 관련하여 온라인에 있는 알고리즘문제를 보니 이전에는 이 두 가지 자료구조를 사용하지 않고 단순하게 배열로 접근하여 풀었던 흔적이 있었다. 42의 경우에도, 워낙 백지 상태에서 만드는 훈련을 시키다보니, 특정 자료구조를 만들어서 효율을 극대화 시키기 보다는 내가 이해할 수 있는 방향으로 무식하게(?) 푸는 것에 익숙해져있어서 배열로만 풀어오던 것이 습관이 되어버린 것 같다.

다행이도, 자바의 경우는 java.util 에서 스택과 큐를 클래스, 인터페이스 등으로 제공해주고 관련 메서드도 모두 포함되어 있기 때문에 죄책감을 느끼지 않고 마구마구 활용해도 좋다!

스택

스택(stack)은 후입선출의 구조를 가진 자료구조다. 클래스로 제공되고 있으며 관련 공식 문서에서 상세하게 볼 수 있다.

Stack (Java Platform SE 7 )

 

Stack (Java Platform SE 7 )

The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item o

docs.oracle.com

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
 
public class stack_test {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<Integer>();
        
        // 스택에 추가하기
        stack.push(1);
        stack.push(2);
        stack.push(3);
        
        // 스택의 상단, 즉 pop을 통해 나올 요소 엿보기
        stack.peek();
        
        // 가장 상단의 값을 꺼내온다. 스택에선 해당 값이 없어지고 x에 그 값이 담긴다.
        Integer x = stack.pop();
        
        // 스택이 비었는지를 확인한다. 
        if (stack.isEmpty())
            System.out.println("The stack is empty!");
    }
}
cs

큐(queue)는 선입선출의 특징을 가진 자료구조다. 자바에서 큐는 인터페이스이기 때문에, LinkedList 같은 클래스로 생성한 뒤 타입 변경을 해주는 방법이 있다.

Queue (Java Platform SE 7 )

 

Queue (Java Platform SE 7 )

A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations. Each of these methods exists in two forms: one throws an exception if the opera

docs.oracle.com

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.*;
 
public class stack_test {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<Integer>();
        
        // 스택에 추가하기
        stack.push(1);
        stack.push(2);
        stack.push(3);
        
        // 스택의 상단, 즉 pop을 통해 나올 요소 엿보기
        stack.peek();
        
        // 가장 상단의 값을 꺼내온다. 스택에선 해당 값이 없어지고 x에 그 값이 담긴다.
        Integer x = stack.pop();
        
        // 스택이 비었는지를 확인한다. 
        if (stack.isEmpty())
            System.out.println("The stack is empty!");
    }
}
cs