반응형
[광고 누르면 오늘의 행운 상승!!]
-
스택과 마찬가지로 삽입과 삭제의 위치가 제한적인 자료구조
-큐의 뒤에서는 삽입만 하고, 큐의 앞에서는 삭제만 이루어지는 구조 -
선입선출구조(FIFO : First In First Out)
-큐에 삽입한 순서대로 원소가 저장되어, 가장 먼저 삽입(First In)된 원소는 가장 먼저 삭제된다
front 가 가리키는 것은 데이터가 있어도 데이터가 없는것과 같다.
한칸 이동해서 실제 데이터가 있는(Rear)로 이동하여 값을 반환하기 때문이다.
구현코드
package Queue;
import java.util.LinkedList;
public class PriorityQueueTest {
public static int[] queue = new int[10];
public static int front = -1;
public static int rear = -1;
public static boolean isEmpty() {
return front == rear;
}
public static boolean isFull() {
return rear == queue.length - 1;
}
public static void enqueue(int item) {
if (isFull()) {
System.out.println("Full");
return;
}
queue[++rear] = item;
int k = rear;
for (int j = rear-1; j >= 0; j--) {
if(queue[j] > queue[k]) {
int T = queue[j]; queue[j] = queue[k]; queue[k] = T;
k=j;
}
}
//빨간부분을 지우면 우선순위 큐, 안지우면 큐
}
public static int dequeue() {
if (isEmpty()) {
System.out.println("empty");
return -1;
}
return queue[++front];
}
public static int qpeek() {
if (isEmpty()) {
System.out.println("empty");
return -1;
}
return queue[front + 1];
}
public static void main(String[] args) {
enqueue(2);
enqueue(3);
enqueue(1);
System.out.println(qpeek());
System.out.println(dequeue());
System.out.println(dequeue());
System.out.println(dequeue());
System.out.println();
}
}
반응형
'4. 자료구조 > 1. 선형(Stack, Queue, List)' 카테고리의 다른 글
ArrayList (0) | 2020.03.02 |
---|---|
PriorityQueue (0) | 2020.03.02 |
Stack (0) | 2020.03.02 |