오늘은
실제 자바 내장 queue를 직접 코딩으로 구현해 보는 시간을 갖겠습니다.
import java.util.Arrays;
import java.util.Queue;
public class MyQueue {
private int[] queue;
private int capacity;
private int front; // 꺼내올 요소의 인덱스
private int rear; // 마지막 추가 요소의 인덱스
private int size; // 요소 개수
public static void main(String[] args) {
MyQueue Q = new MyQueue();
Q.enqueue(1);
Q.enqueue(2);
Q.enqueue(3);
Q.enqueue(4);
Q.enqueue(5);
Q.dequeue();
Q.dequeue();
Q.dequeue();
Q.dequeue();
Q.dequeue();
System.out.println("사이즈 " + Q.size());
System.out.println("peek(가장 첫번째 값) " + Q.peek());
System.out.println("리어(인덱스) " + Q.rear());
System.out.println("isEmpty: " + Q.isEmpty());
System.out.println("isFull: " + Q.isFull());
}
public MyQueue() {
this.queue = new int[5];
this.capacity = this.queue.length;
this.front = -1;
this.rear = -1;
this.size = 0;
}
public void enqueue(int data) { // 큐에 값을 입력하는 함수
if (rear != queue.length) {
queue[++rear] = data;
size++;
}
}
public int rear() { // 현재 rear 값을 가져오는 함수
return rear;
}
public int peek() { // 가장 첫번째 값을 반환하는 함수
return queue[front + 1];
}
public boolean isEmpty() { // 큐가 비어있는지 확인하는 함수
return size == 0;
}
public int size() { // 큐에 현재 들어있는 값의 개수를 확인하는 함수
return size;
}
public void dequeue() { // 큐의 첫번째 값을 없애는 함수
if (!isEmpty()) {
front = (front + 1) % size;
size--;
System.out.println("프론트 값: " + front);
}
}
public boolean isFull() {
return size == capacity;
}
}
해당 코드는 2022년 10월 2일 스터디 모임을 통해 스터디원들과 함께 구현한 코드입니다.
'알고리즘 > 구현' 카테고리의 다른 글
알고리즘_MinHeap(최소힙) (1) | 2022.11.10 |
---|---|
알고리즘_ArrayList (0) | 2022.11.10 |
알고리즘_LinkedList(리스트) (0) | 2022.11.10 |
알고리즘_이진트리 (0) | 2022.10.20 |