这是使用链接列表的优先级队列的代码
我在这段代码中有两个疑问
1)此代码是我的插入功能的一部分
if((*addofhead)->priority <= newnode->priority ){
struct node* temp=*addofhead;
while(temp->next!=NULL&&temp->priority <newnode->priority ){
temp=temp->next;
}
newnode->next=temp->next;
temp->next=newnode;
return;
}
为什么我们不能在
while
循环而不是temp->next!=NULL
中执行temp!= NULL的原因,因为temp!=NULL
也会使循环在另一次迭代中退出,但它崩溃了是崩溃的原因2)我想制作一个优先级队列,以使优先级最低的元素
应该先删除,然后再删除优先级相同的元素,然后先删除该元素,然后再添加
main
功能的输入部分 insert(&head,3,5);
insert(&head,2,2);
insert(&head,1,1);
insert(&head,7,1);
insert(&head,11,1);
insert(&head,8,5);
insert(&head,9,5);
我正在为此
1 2 11 7 3 8 9
获得输出,但其输出应为1 7 11 2 3 8 9
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
int priority;
struct node* next;
};
struct node* getnewnode(int data,int priority){
struct node* newnode=malloc(sizeof(struct node));
newnode->data=data;
newnode->next=NULL;
newnode->priority=priority;
return newnode;
}
void insert(struct node** addofhead,int data,int priority){
struct node* newnode=getnewnode(data,priority);
if(*addofhead==NULL){
*addofhead=newnode;
printf("head in insert is %d",*addofhead);
return;
}
if((*addofhead)->priority > newnode->priority){
newnode->next=*addofhead;
*addofhead=newnode;
return;
}
if((*addofhead)->priority <= newnode->priority ){
struct node* temp=*addofhead;
while(temp->next!=NULL&&temp->priority <newnode->priority ){
temp=temp->next;
}
newnode->next=temp->next;
temp->next=newnode;
return;
}
}
int removee(struct node** head){
if(*head==NULL)
return -1;
int temp=(*head)->data;
*head=(*head)->next;
return temp;
}
int main(){
struct node* head=NULL;
insert(&head,3,5); /// 3
insert(&head,2,2); /// 2,3
insert(&head,1,1); /// 1,2,3
insert(&head,7,1);
insert(&head,11,1);
insert(&head,8,5); /// 1,7,2,3
insert(&head,9,5);
struct node* temp=head;
while(temp)
{
printf(" %d ",temp->data);
temp=temp->next;
}
printf("\n head in main after insertion is %d",head);
}
最佳答案
为什么我们不能在while循环中使用temp!=NULL
代替temp->next!=NULL
(?)
因为循环后的行具有temp->next;
@Jonathan Leffler。
前进要插入的链表的通常目标是知道前一个节点的指针,以便可以更新其.next
成员。
代码有2个功能问题
比较错误的优先级
// while(temp->next!=NULL&&temp->priority <newnode->priority ){
while(temp->next!=NULL&&temp->next->priority <newnode->priority ){
// ^^^^^^
==时比较不正确
// while(temp->next!=NULL&&temp->next->priority <newnode->priority ){
while(temp->next!=NULL&&temp->next->priority <= newnode->priority ){
// ^^^^^^ ^^
也可以使用
%p
打印void *
,而不使用"%d"
打印指针。// printf("head in insert is %d",*addofhead);
printf("head in insert is %p",(void *) (*addofhead));
进行此操作非常有用的是创建一个辅助函数来打印数据。然后,在每次插入后都可以轻松调用它以缩小问题范围。
void pq(const struct node* p) {
while (p) {
printf("(data %d,pri %d) ", p->data, p->priority);
p = p->next;
}
puts("");
}
我发现OP的
insert()
过于复杂。请参见@wildplasser。关于c - 优先级队列未按升序插入元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52629399/