
[출처] : https://inpa.tistory.com/entry/JCF-🧱-Stack-구조-사용법-정리
| 메서드 | 설명 |
|---|---|
| boolean empty() | Stack이 비어있는지 알려준다 |
| Object peek() | Stack의 맨 위에 저장된 객체를 반환. pop과 달리 Stack에서 객체를 꺼내지는 않는다. 비어있을 경우 EmptyStackException 발생 |
| Object pop() | Stack의 맨 위에 저장된 객체를 꺼낸다. 비어있을 경우 EmptyStackException 발생 |
| Object push(Object item) | Stack에 객체(item)를 저장한다 |
| int search(Object o) | Stack에서 주어진 객체(o)를 찾아서 그 위치를 반환 |
못 찾을 경우 -1을 반환
배열과 달리 위치는 0이 아닌 1부터 시작 |
/* Stack 처럼 사용하기 */
Deque<String> stack = new ArrayDeque<>();
stack.push("a");
stack.push("b");
stack.push("c");
stack.push("d");
stack.push("e");
System.out.println(stack); // [a, b, c, d, e]
System.out.println(stack.pop()); // e
System.out.println(stack.pop()); // d
System.out.println(stack); // [a, b, c]
import java.util.LinkedList;
import java.util.Queue;
Queue<Integer> q = new LinkedList<>(); // int형 queue 선언
Queue<String> q = new LinkedList<>(); // String형 queue 선언
Queue<Integer> q = new LinkedList<>(); // int형 queue 선언
q.offer(3);
q.offer(5);
q.offer(1);
q.offer(4);
System.out.println(q); // 출력 결과 : [3, 5, 1, 4]
→ add()를 사용해서 값 추가할 수 있다. 차이점은 add()는 예외 발생, offer()은 false 리턴
Queue<Integer> q = new LinkedList<>(); // int형 queue 선언
q.offer(3);
q.offer(5);
q.offer(1);
q.offer(4);
q.poll();
System.out.println(q); // 출력 결과 : [5, 1, 4]
q.clear();
System.out.println(q); // 출력 결과 : []
Queue<Integer> q = new LinkedList<>(); // int형 queue 선언
q.offer(3);
q.offer(5);
q.offer(1);
q.offer(4);
System.out.println(q.peek()); // 출력 결과 : 3