java实现优先级队列

优先级队列是一种带有优先级的队列,我们约定关键字最小的数据元素具有最高的优先级,且总是排在队首。

在优先级中的数据元素也不仅仅限制在队尾进行,而是顺序插入到合适的位置,以确保队列的优先级顺序。

实现只有在入队的时候和队列又些区别,用到了之前写的结点Node类

队列接口:

package queueTest;

public interface IQueue {
	public void clear();

	public boolean isEmpty();

	public int length();

	public Object peek();// 取队首元素

	public void offer(Object x) throws Exception;// 入队

	public Object poll();// 出队

	public void display();
}


优化结点的data类:

package queueTest;

public class PriorityQData {
	//结点的data类
	public Object elem;//结点的数据元素值
	public int priority;//结点的优先级
	public PriorityQData(Object elem, int priority) {
		this.elem = elem;
		this.priority = priority;
	}
}

实现IQueue的优先级队列:

package queueTest;

import linearList.Node;

public class PriorityQueue implements IQueue {

	private Node front;//队首的引用
	private Node rear;//队尾的引用
	
	
	public PriorityQueue() {
		front=rear=null;
	}

	@Override
	public void clear() {
		front=rear=null;
	}

	@Override
	public boolean isEmpty() {
		return front==null;
	}

	@Override
	public int length() {
		Node p=front;
		int length=0;
		while(p!=null){
			p=p.next;
			length++;
		}
		return length;
	}

	@Override
	public Object peek() {
		if(front==null){
			return null;
		}
		else{
			return front.data;
		}
	}

	@Override
	public void offer(Object x) throws Exception {
		PriorityQData pn=(PriorityQData)x;
		Node s=new Node(pn);//构造数据域为pn的结点
		if(front==null){
			front=rear=s;
		}
		else {
			Node p=front;
			Node q=front;
			while(p!=null&&pn.priority>=((PriorityQData)p.data).priority){
				q=p;
				p=p.next;
			}
			if(p==null){
				rear.next=s;
				rear=s;
			}
			else if (p==front) {
				s.next=front;
				front=s;
			}
			else {
				q.next=s;
				s.next=p;
			}
		}
	}

	@Override
	public Object poll() {
		if(front==null){
			return null;
		}
		else{
			return front.data;
		}
	}

	@Override
	public void display() {
		if(!isEmpty()){
			Node p=front;
			while(p!=rear.next){
				PriorityQData q=(PriorityQData)p.data;
				System.out.println(q.elem+" "+q.priority);
				p=p.next;
			}
		}
		else {
			System.out.println("此队列为空");
		}
	}

}

测试:

package queueTest;

public class ProcessManagement {

	public static void main(String[] args) throws Exception {
		PriorityQueue pm=new PriorityQueue();
		pm.offer(new PriorityQData(1, 20));
		pm.offer(new PriorityQData(2, 30));
		pm.offer(new PriorityQData(3, 20));
		pm.offer(new PriorityQData(4, 20));
		pm.offer(new PriorityQData(5, 40));
		pm.offer(new PriorityQData(6, 10));
		pm.display();
	}

}

输出:

6 10
1 20
3 20
4 20
2 30
5 40


你可能感兴趣的:(Java,数据结构)