Queue+PriorityQueue

u010660276發表於2014-01-03

java中的佇列Queue是一個介面,LinkedList提供了方法來支援佇列,所以可以作為佇列的一種實現方法

其中peek用來返回隊頭,不移除,佇列為空時返回null

offer將元素插入隊尾;

poll和remove再返回隊頭元素的基礎上刪除元素,poll在佇列為空時返回null。

import java.util.*;
public class QueueDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Queue<Integer> q=new LinkedList<Integer>();
		Random rand=new Random(100);
		for(int i=0;i<10;i++){
			q.offer(rand.nextInt(100));
		}
		while(q.poll()!=null){
			System.out.print(q.remove()+" ");
		}
		System.out.println();

	}

}

優先佇列在java中有了實現,要想在PriorityQueue中使用自己的類,類中要實現Comparable介面生成自然順序,或者自己提供Comparator。

import java.util.*;
public class QueueDemo {

	public static void printQ(Queue q){//這個Queue不用指明型別,挺神奇的
		while(q.peek()!=null){
			System.out.print(q.poll()+" ");
		}
		System.out.println();
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		PriorityQueue<Integer> p=new PriorityQueue<Integer>();
		Random rand=new Random(47);
		for(int i=0;i<10;i++)
			p.offer(rand.nextInt(100));
		printQ(p);
		List<Integer> list=Arrays.asList(25,22,20,48,19,6,53,132,21);
		p=new PriorityQueue<Integer>(list);
		printQ(p);
		p=new PriorityQueue<Integer>(list.size(),Collections.reverseOrder());//長生反序佇列
		printQ(p);
		p.addAll(list);
		printQ(p);

	}

}