PriorityQueue 优先级队列

本文介绍了一个基于链表实现的优先级队列数据结构,该队列假设数值越大优先级越高,并提供了入队、出队及判断是否为空等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

提供一个基于链表的优先级队列,为了简便,只存储整数,假设数值越大,优先级越高。

工作时该队列按照数值的大小排列,出队时出优先级别最高的元素。

这已经不是普通意义上的队列(先进先出),叫优先级队列只是习惯。

put:入队

get:出队

isEmpty:是否为空

普通队列请参见LinkedQueueQueue

相对与另一个实现(PriorityQueue),这个优先级队列没有容量的限制。

Node是辅助类,提供节点的数据结构,为了简便,没有使用标准的set,get

class Node {
	private int value;
	private Node next;

	Node(int value) {
		this.value = value;
	}

	int value() {
		return value;
	}

	Node next() {
		return next;
	}

	void next(Node next) {
		this.next = next;
	}
}
 
class PriorityQueue {
	private Node top;

	void put(int value) {
		Node node = new Node(value);
		if(top == null || top.value() <= value) {
			node.next(top);
			top = node;
		} else {
			Node temp = top.next();
			Node previous = top;
			while(temp != null) {
				if(temp.value() <= value) break;
				previous = temp;
				temp = temp.next();
			}
			node.next(previous.next());
			previous.next(node);
		}
	}

	int get() {
		assert top != null;
		int result = top.value();
		top = top.next();
		return result;
	}

	boolean isEmpty() {
		return top == null;
	}
	
	//测试代码
	public static void main(String[] args) {
		PriorityQueue q = new PriorityQueue();	
		assert q.isEmpty();
		q.put(10);
		q.put(5);
		q.put(20);
		assert !q.isEmpty();
		assert q.get() == 20;
		assert q.get() ==  10;
		assert q.get() == 5;
		assert q.isEmpty();
	}
}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值