尝试实现优先级队列插入 dev c++ IDE),即在优先级 > 新节点优先级的节点之前。来自用户的插入似乎发生在命令提示符下,但显示功能仅输出第一个节点。为什么没有显示其他队列元素?恐怕它们没有被首先插入,这就是为什么在随后插入 10,20,30 然后删除..它打印空队列..因为队列只有 10..为什么?请建议。
注意:我没有在代码中包含delete和main函数,但它在程序中,显然..没有发生运行时异常..编译工作正常。但没有想要的输出。
#include<iostream>
using namespace std;
typedef struct node{ //template would enable generic datatype
int info,prn;
node * link;
}node;
node * start = 0;
int item,pri;
void insert(int item, int pri){
node * newnode = new node;
newnode-> info = item;
newnode-> prn = pri;
if(start == 0){//explicit check in insert if start is NULL.
start = newnode;
newnode->link = 0;
}
/*When you first run the program, start = 0 or NULL. You then say prev = start,
so as a result prev = NULL. So when you try to access prev->link, there's an access violation.*/
else{
node * prev= start;
node * temp = prev->link;
while (temp!= 0){
if(temp->prn > newnode->prn){
newnode -> link = prev -> link;
prev -> link = newnode;
break;
}
else{
if( temp->link == 0){
temp -> link = newnode;
newnode->link = 0;
break;
}
}
prev = prev->link;
}
}
}
void display(){
if(start == 0)
cout<<"Empty priority queue\n";
else{
cout<<("The Contents of the List are: ");
node *temp = start;
while(temp!=NULL){ //if we do while temp->link!=NULL, then last node won't print
cout<< temp->info;
cout<<" ---> ";
temp = temp->link;
}
}
}