자바에서 배열을 사용하여 스택(Stack)과 큐(Queue)를 구현하는 것은 데이터 구조를 이해하고 다루는 데 중요한 과제입니다. 스택은 후입선출(LIFO, Last-In-First-Out)의 원리를 따르며, 큐는 선입선출(FIFO, First-In-First-Out)의 원리를 따릅니다.
1. 배열을 사용한 스택 구현 예제
public class StackExample {
private int maxSize;
private int top;
private int[] stackArray;
public StackExample(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1; // 스택이 비어있을 때
}
public void push(int value) {
if (top < maxSize - 1) {
stackArray[++top] = value;
} else {
System.out.println("스택이 가득 찼습니다.");
}
}
public int pop() {
if (top >= 0) {
return stackArray[top--];
} else {
System.out.println("스택이 비어 있습니다.");
return -1; // 에러 값을 반환
}
}
public boolean isEmpty() {
return top == -1;
}
public int peek() {
return stackArray[top];
}
public static void main(String[] args) {
StackExample stack = new StackExample(5);
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Top 값: " + stack.peek()); // 3
System.out.println("Pop 값: " + stack.pop()); // 3
System.out.println("Top 값: " + stack.peek()); // 2
}
}
2. 배열을 사용한 큐 구현 예제
public class QueueExample {
private int maxSize;
private int front;
private int rear;
private int[] queueArray;
public QueueExample(int size) {
maxSize = size;
queueArray = new int[maxSize];
front = 0;
rear = -1; // 큐가 비어있을 때
}
public void insert(int value) {
if (rear == maxSize - 1) {
System.out.println("큐가 가득 찼습니다.");
} else {
queueArray[++rear] = value;
}
}
public int remove() {
if (front > rear) {
System.out.println("큐가 비어 있습니다.");
return -1; // 에러 값을 반환
} else {
return queueArray[front++];
}
}
public boolean isEmpty() {
return (front > rear);
}
public int peek() {
return queueArray[front];
}
public static void main(String[] args) {
QueueExample queue = new QueueExample(5);
queue.insert(1);
queue.insert(2);
queue.insert(3);
System.out.println("Front 값: " + queue.peek()); // 1
System.out.println("Remove 값: " + queue.remove()); // 1
System.out.println("Front 값: " + queue.peek()); // 2
}
}
이러한 스택과 큐의 간단한 배열 구현은 개념을 이해하고 연습하는 데 유용합니다. 스택과 큐는 데이터 구조와 알고리즘에서 중요한 역할을 하며, Java의 내장 라이브러리로도 구현할 수 있습니다. Java에서는 java.util.Stack 및 java.util.LinkedList를 사용하여 스택 및 큐를 구현할 수도 있습니다.
With ChatGPT
'JAVA > 포스팅' 카테고리의 다른 글
자바 배열 동적 데이터 관리 (0) | 2023.11.03 |
---|---|
자바 배열을 매개변수로 받는 함수 (0) | 2023.11.03 |
자바 배열 데이터 필터링 및 변환 (0) | 2023.11.03 |
자바 배열 데이터 검색 (0) | 2023.11.03 |
자바 배열 데이터 정렬 (0) | 2023.11.03 |