LinkedList provides a method to support the behavior of the queue, and it implements the queue interface, so linkedlist can be used as an implementation of the queue.
Package Cn.usst.queue.demo;import Java.util.linkedlist;import Java.util.queue;import java.util.random;/* * Basic use of queue */public class Queuedemo {public static void main (string[] args) {queue<integer> queue = new LINKEDLIST&L T;integer> (); Random random = new random, for (int i=0; i<10; i++) {Queue.offer (Random.nextint (I+10));} PRINTQ (queue); Queue<character> QC = new linkedlist<character> (); 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 () insert an element into the end of the team * PEEK () and element () are all returned in the case of removal of the team header * Peek () method returns Null,element () when the queue is empty Throws a Nosuchelementexception Exception * poll () and the Remove () method will remove and return the team header * poll () to return NULL when the queue is empty, and remove () Throws a Nosuchelementexception exception */
Priorityqueue: Implementation of the 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<integer> priorityqueue = new priorityqueue<integer> (); Random rand = new Random (), for (int i=0; i<10; i++) {Priorityqueue.offer (Rand.nextint (I+10));} PRINTQ (Priorityqueue); list<integer> ints = arrays.aslist (9, 8, 2, 4, 7);p riorityqueue = new PRIORITYQUEUE<INTEGER&G t; (ints);p RINTQ (priorityqueue);//Reverse Output Priorityqueue = new Priorityqueue<integer> (Ints.size (), Collections.reverseorder ());p Riorityqueue.addall (ints);p RINTQ (priorityqueue);} private static void Printq (queue queue) {while (Queue.peek ()!=null) {System.out.println (Queue.remove () + "");} System.out.println ();}}
Using LinkedList to implement a queue in Java