我在构建基于PList的优先级队列时遇到问题。基本上,如果我添加项目,当我运行main函数时它所做的就是吐出最高和最低优先级值。
这是我的PQueue插入项目方法
public class PQueue {
PList pq;
PList top;
public PQueue(){
this.pq=null;
}
public PQueue(int priority, char x){
this.pq=new PList(x, priority, null);
top=this.pq;
}
public boolean isEmpty(){
if(this.pq==null){
return true;
}else{
return false;
}
}
public void insertItem(int priority, char x){
if(isEmpty()){
this.pq=new PList(x, priority);
top=this.pq;
}else{
PList p=top;
while(p.priority<top.priority && p!=null){
p=p.next;
}PList n=new PList(x, priority, p.next);
p.next=n;
if(n.priority>top.priority){
top=n;
}
}
}
public void show(PrintStream p){
PList prnt= top;
while(prnt!=null){
p.println(prnt.content);
prnt=prnt.next;
}
}
}
这是我的链表::
package se2s03;
public class PList {
public char content;
public int priority;
public PList next;
PList(final char a, final int b, final PList ll){
this.content=a;
this.priority=b;
this.next=ll;
}
PList(final char a, final int b){
this.content=a;
this.priority=b;
}
}
答案 0 :(得分:0)
这是使用链表的优先级队列实现。
public class PQueue
{
private Node head;
public boolean isEmpty()
{
return head == null;
}
public void insert(int priority, Object obj)
{
if (head == null)
head = new Node(obj, priority);
else {
Node curr = head, prev = null;
while (curr != null && curr.priority > priority) {
prev = curr;
curr = curr.next;
}
if (prev == null)
head = new Node(obj, priority, head);
else
prev.next = new Node(obj, priority, curr);
}
}
public Object remove()
{
if (head == null)
return null;
Object val = head.val;
head = head.next;
return val;
}
public Object peek()
{
if (head == null)
return null;
return head.val;
}
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("[");
Node prnt = head;
while (prnt != null) {
sb.append(prnt.val.toString() + ", ");
prnt = prnt.next;
}
return sb.substring(0, sb.length() - 2) + "]";
}
private class Node
{
Object val;
int priority;
Node next;
Node(Object val, int priority)
{
this(val, priority, null);
}
Node(Object val, int priority, Node next)
{
this.val = val;
this.priority = priority;
this.next = next;
}
}
public static void main(String[] args)
{
PQueue pq = new PQueue();
for (char ch = 'a'; ch <= 'z'; ch++)
pq.insert(ch - 'a', ch);
System.out.println(pq);
while (!pq.isEmpty())
System.out.print(pq.remove() + ", ");
}
}