먼저 넣은 데이터가 먼저 나오는 FIFO(First in First out) 구조로 저장하는 자료 구조
(이미지 출처 : https://buildgoodhabit.tistory.com/142)
public static class ArrayQueue {
private int front, rear, size;
private int capacity;
private int array[];
public ArrayQueue(int capacity) {
this.capacity = capacity;
front = this.size = 0;
rear = capacity - 1;
array = new int[this.capacity];
}
public boolean isFull(ArrayQueue queue) {
return queue.size == queue.capacity;
}
public boolean isEmpty(ArrayQueue queue) {
return queue.size == 0;
}
public void enqueue(int item) {
if (isFull(this)) return;
this.rear = (this.rear + 1) % this.capacity;
this.array[this.rear] = item;
this.size++;
System.out.println(item + " enqueued to queue");
}
public int dequeue() {
if (isEmpty(this)) return Integer.MIN_VALUE;
int item = this.array[this.front];
this.front = (this.front + 1) % this.capacity;
this.size--;
return item;
}
public int getFront() {
if (isEmpty(this)) {
return Integer.MIN_VALUE;
}
return this.array[this.front];
}
public int getRear() {
if (isEmpty(this)) {
return Integer.MIN_VALUE;
}
return this.array[this.rear];
}
}
public static class QNode {
int key;
QNode next;
public QNode(int key) {
this.key = key;
this.next = null;
}
}
public static class LinkedListQueue {
private QNode front, rear;
public LinkedListQueue() {
this.front = this.rear = null;
}
public void enqueue(int key) {
QNode temp = new QNode(key);
if (this.rear == null) {
this.front = this.rear = temp;
return;
}
this.rear.next = temp;
this.rear = temp;
}
public void dequeue() {
if (this.front == null) {
return;
}
QNode temp = this.front;
this.front = this.front.next;
if (this.front == null) {
this.rear = null;
}
}
}
public class MyDequeue {
private MyNode front, rear;
public void pushFront(int data) {
if (front == null) {
this.front = this.rear = new MyNode(data);
} else {
MyNode temp = new MyNode(data);
temp.next = this.front;
this.front.prev = temp;
this.front = temp;
}
System.out.println(data + " front pushed to dequeue");
}
public void pushBack(int data) {
if (rear == null) {
this.front = this.rear = new MyNode(data);
} else {
MyNode temp = new MyNode(data);
temp.prev = this.rear;
this.rear.next = temp;
this.rear = temp;
}
System.out.println(data + " back pushed to dequeue");
}
public int popFront() {
if (this.front == null) {
System.out.println("Empty Dequeue");
return -1;
}
MyNode temp = this.front;
this.front = this.front.next;
this.front.prev = null;
return temp.data;
}
public int popBack() {
if (this.rear == null) {
System.out.println("Empty Dequeue");
return -1;
}
MyNode temp = this.rear;
this.rear = this.rear.prev;
this.rear.next = null;
return temp.data;
}
public class MyNode {
MyNode prev;
MyNode next;
int data;
MyNode(int data) {
this.data = data;
}
}
}