
스택은 '후입선출(LIFO, Last In First Out)' 구조를 가진다.
이 말은 가장 나중에 추가된 요소가 가장 먼저 나간다는 뜻이다. 생각해보면 접시 더미와 비슷하다. 새 접시는 더미의 맨 위에 올리고, 접시를 가져갈 때도 맨 위의 것을 먼저 가져간다. 자바에서는 Stack 클래스를 사용하여 스택을 구현한다. 기본적인 메소드로는 push (요소 추가), pop (맨 위 요소 제거 및 반환), peek (맨 위 요소 확인), isEmpty (스택이 비었는지 확인) 등이 있다.
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
// 스택 생성
Stack<Integer> stack = new Stack<>();
// 요소 추가 (push)
stack.push(1);
stack.push(2);
stack.push(3);
// 스택 상태 출력
System.out.println("스택: " + stack); // 스택: [1, 2, 3]
// 맨 위의 요소 확인 (peek)
int top = stack.peek();
System.out.println("맨 위의 요소: " + top); // 맨 위의 요소: 3
// 요소 제거 (pop)
while (!stack.isEmpty()) {
int removedItem = stack.pop();
System.out.println("제거된 요소: " + removedItem);
// 첫 번째 반복: 제거된 요소: 3
// 두 번째 반복: 제거된 요소: 2
// 세 번째 반복: 제거된 요소: 1
}
// 최종 스택 상태 출력
System.out.println("최종 스택: " + stack); // 최종 스택: []
}
}

큐는 '선입선출(FIFO, First In First Out)' 구조를 가진다.
즉, 가장 먼저 추가된 요소가 가장 먼저 나간다. 이는 마치 사람들이 줄을 서서 기다리는 것과 같다. 먼저 온 사람이 먼저 서비스를 받고 떠난다. 자바에서는 주로 LinkedList 클래스를 사용하여 큐를 구현하거나, Queue 인터페이스를 구현한 다양한 클래스들을 사용할 수 있다. 주요 메소드로는 add 또는 offer (요소 추가), remove 또는 poll (요소 제거 및 반환), peek (큐의 맨 앞 요소 확인) 등이 있다.
import java.util.LinkedList;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
// 큐 생성
Queue<Integer> queue = new LinkedList<>();
// 요소 추가 (offer)
queue.offer(1); // 1 추가
queue.offer(2); // 2 추가
queue.offer(3); // 3 추가
// 큐 상태 출력
System.out.println("큐: " + queue); // 큐: [1, 2, 3]
// 맨 앞의 요소 확인 (peek)
int first = queue.peek();
System.out.println("맨 앞의 요소: " + first); // 맨 앞의 요소: 1
// 요소 제거 (poll)
while (!queue.isEmpty()) {
int removedItem = queue.poll();
System.out.println("제거된 요소: " + removedItem);
// 첫 번째 반복: 제거된 요소: 1
// 두 번째 반복: 제거된 요소: 2
// 세 번째 반복: 제거된 요소: 3
}
// 최종 큐 상태 출력
System.out.println("최종 큐: " + queue); // 최종 큐: []
}
}
스택과 큐는 데이터를 저장하고 처리하는 방식이 매우 달라, 사용하는 상황에 따라 적절한 선택이 필요하다. 예를 들어, 뒤집어야 하는 데이터나 최근 이벤트를 처리할 때는 스택을, 처리 순서가 중요한 작업 대기열이나 데이터 스트리밍에는 큐를 사용한다.
package com.mystudy.stack_queue;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class Stack_Queue {
public static void main(String[] args) {
// 스택 섹션
System.out.println("=== 스택(Stack) : LIFO - 후입선출 ====");
// 스택 생성
Stack<String> stack = new Stack<String>();
// 스택에 요소 추가
stack.push("1.첫째");
stack.push("2.둘째");
stack.push("3.셋째");
stack.push("4.넷째");
// 스택의 현재 상태, 크기, 특정 요소의 위치 출력
System.out.println(stack);
System.out.println("stack.size() : " + stack.size());
System.out.println("stack.seach(\"3.셋째\") : " + stack.search("3.셋째"));
// 스택의 맨 위 요소 확인
System.out.println("--- peek() ---");
System.out.println("stack.peek() : " + stack.peek());
System.out.println("stack.size() : " + stack.size());
// 스택에서 요소 제거하며 출력
System.out.println("-------------- pop() ----------------");
while (!stack.empty()) {
System.out.println("stack.pop() : " + stack.pop());
}
// 스택이 비어있는지 확인
System.out.println("stack.size() : " + stack.size());
System.out.println("stack.empty() : " + stack.empty());
// 큐 섹션
System.out.println("================= 큐(Queue) ==================");
// 큐 생성
Queue<String> queue = new LinkedList<String>();
// 큐에 요소 추가
queue.offer("1.첫째");
queue.offer("2.둘째");
queue.offer("3.셋째");
queue.offer("4.넷째");
// 큐의 현재 상태와 크기 출력
System.out.println(queue);
System.out.println(queue.size());
// 큐의 맨 앞 요소 확인
System.out.println("---- peek() ----");
String data = queue.peek();
System.out.println("peek data : " + data);
System.out.println("queue.peek() : " + queue.peek());
System.out.println("queue.size() : " + queue.size());
// 큐에서 요소 제거하며 출력
System.out.println("--- poll() ---");
while (!queue.isEmpty()) {
System.out.println("queue.poll() : " + queue.poll());
}
// 큐가 비어있는지 확인
System.out.println("queue.size() : " + queue.size());
System.out.println("queue.isEmpty() : " + queue.isEmpty());
System.out.println(queue);
}
}
=== 스택(Stack) : LIFO - 후입선출 ====
[1.첫째, 2.둘째, 3.셋째, 4.넷째]
stack.size() : 4
stack.seach("3.셋째") : 2
--- peek() ---
stack.peek() : 4.넷째
stack.size() : 4
-------------- pop() ----------------
stack.pop() : 4.넷째
stack.pop() : 3.셋째
stack.pop() : 2.둘째
stack.pop() : 1.첫째
stack.size() : 0
---- 스택 전체데이터 조회 ----
stack.empty() : true
stack.empty() : true
stack.size() : 0
================= 큐(Queue) ==================
[1.첫째, 2.둘째, 3.셋째, 4.넷째]
4
---- peek() ----
peek data : 1.첫째
queue.peek() : 1.첫째
queue.peek() : 1.첫째
queue.size() : 4
--- poll() ---
queue.poll() : 1.첫째
queue.poll() : 2.둘째
queue.poll() : 3.셋째
queue.poll() : 4.넷째
queue.size() : 0
queue.isEmpty() : true
[]
------ Queue 전체 데이터 추출(사용) ------