자바 에서 LinkedList 를 사용 하여 Queue 구현
2120 단어 알고리즘 소 역
package cn.usst.queue.demo;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
/*
* Queue
*/
public class QueueDemo {
public static void main(String[] args) {
Queue queue = new LinkedList();
Random random = new Random(47);
for(int i=0; i<10; i++){
queue.offer(random.nextInt(i+10));
}
printQ(queue);
Queue qc = new LinkedList();
for(char c : "Brontosaurus".toCharArray()){
qc.offer(c);
}
printQ(qc);
}
private static void printQ(Queue queue) {
while(queue.peek() !=null ){
System.out.println(queue.remove() + " ");
}
System.out.println();
}
}
/*
* Offer()
* peek() element()
* peek() null,element() NoSuchElementException
* poll() remove()
* poll() null, remove() NoSuchElementException
*/
Priority Queue:우선 대기 열의 실현
package cn.usst.queue.demo;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
public class PriorityQueueDemo {
public static void main(String[] args) {
PriorityQueue priorityQueue = new PriorityQueue();
Random rand = new Random();
for(int i=0; i<10; i++){
priorityQueue.offer(rand.nextInt(i+10));
}
printQ(priorityQueue);
List ints = Arrays.asList(25, 22, 20, 18, 14, 9, 8, 2, 4, 7);
priorityQueue = new PriorityQueue(ints);
printQ(priorityQueue);
//
priorityQueue = new PriorityQueue(ints.size(), Collections.reverseOrder());
priorityQueue.addAll(ints);
printQ(priorityQueue);
}
private static void printQ(Queue queue) {
while(queue.peek() !=null ){
System.out.println(queue.remove() + " ");
}
System.out.println();
}
}