스택 (Stack)
개념:
- 스택은 LIFO (Last-In-First-Out) 구조를 사용하는 자료구조
장점:
- 간단한 구현
- 빠른 삽입 및 삭제
단점:
- 특정 데이터에 접근하기 어려움
자바 예제 코드:
public class StackExample {
private static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
private Node top;
public void push(int data) {
Node newNode = new Node(data);
newNode.next = top;
top = newNode;
}
public int pop() {
if (isEmpty()) {
throw new IllegalStateException("Stack is empty");
}
int data = top.data;
top = top.next;
return data;
}
public boolean isEmpty() {
return top == null;
}
public static void main(String[] args) {
StackExample stack = new StackExample();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop()); // 3
System.out.println(stack.pop()); // 2
System.out.println(stack.pop()); // 1
}
}
큐 (Queue)
개념:
- 큐는 FIFO (First-In-First-Out) 구조를 사용하는 자료구조.
장점:
- 간단한 구현
- 특정 데이터에 접근하기 쉬움
단점:
- 특정 데이터를 삭제하기 어려움
자바 예제 코드:
public class QueueExample {
private static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
private Node front;
private Node rear;
public void enqueue(int data) {
Node newNode = new Node(data);
if (isEmpty()) {
front = rear = newNode;
} else {
rear.next = newNode;
rear = newNode;
}
}
public int dequeue() {
if (isEmpty()) {
throw new IllegalStateException("Queue is empty");
}
int data = front.data;
front = front.next;
if (front == null) {
rear = null;
}
return data;
}
public boolean isEmpty() {
return front == null;
}
public static void main(String[] args) {
QueueExample queue = new QueueExample();
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
System.out.println(queue.dequeue()); // 1
System.out.println(queue.dequeue()); // 2
System.out.println(queue.dequeue()); // 3
}
}
덱 (Deque)
개념:
- 덱은 양쪽 끝에서 데이터를 삽입 및 삭제할 수 있는 자료구조.
- 스택과 큐의 기능을 모두 가지고 있음
- LIFO 및 FIFO 방식으로 모두 작동할 수 있음
장점:
- 다양한 기능 제공
- 데이터 접근 및 삭제 유연성
단점:
- 구현이 상대적으로 복잡
자바 예제 코드:
public class DequeExample {
private static class Node {
int data;
Node prev;
Node next;
public Node(int data) {
this.data = data;
}
}
private Node head;
private Node tail;
public void addFirst(int data) {
Node newNode = new Node(data);
if (isEmpty()) {
head = tail = newNode;
} else {
newNode.next = head;
head.prev = newNode;
'개인 블로그' 카테고리의 다른 글
[각코 6주차 개인 블로그] 트리, 해싱 (0) | 2024.02.09 |
---|---|
[모각코 4주차 개인블로그] 이진탐색 (0) | 2024.02.09 |
[모각코 3주차 개인블로그] 정렬 (0) | 2024.02.09 |
[모각코 2주차 개인 블로그] 배열과 연결리스트 (0) | 2024.02.09 |
[모각코 1주차 개인 블로그] JAVA 기본 문법 복습 (1) | 2024.01.10 |