指针未在c中的insert中修改

优先级队列的程序,我对指针有疑问,我正在通过头插入但是它没有在插入中修改,因为你可以看到我在插入中打印头和插入中的主要是打印非零的东西在头部它是零

#include #include 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* head,int data,int priority){ struct node* newnode=getnewnode(data,priority); if(head==NULL){ head=newnode; printf("head in insert is %d",head); return; } if(head->priority > newnode->priority){ newnode->next=head; head=newnode; return; } if(head->priority priority ){ struct node* temp=head; while(temp->priority 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); printf("\n head in main is %d",head); } 

head in insertinsert函数的局部,对它的任何修改都不会影响main中的head并且一旦控件退出insert函数就会被破坏。

解:

你需要在main传递head的指针才能insert

因此,您的插入将变为如下。

  void insert(struct node **head,int data,int priority){ struct node* newnode=getnewnode(data,priority); if(*head==NULL){ *head=newnode; printf("head in insert is %d",*head); return; } if((*head)->priority > newnode->priority){ newnode->next=*head; *head=newnode; return; } if((*head)->priority <= newnode->priority ){ struct node* temp=*head; while(temp->priority <= newnode->priority && temp->next != NULL){ temp=temp->next; } newnode->next=temp->next; temp->next=newnode; return; } } 

然后从main调用insert ,如下所示。

 insert(&head,3,5); 

没有任何if()语句的超简化版本:


 void insert(struct node **head, int data, int priority){ struct node *newnode = getnewnode(data, priority); for( ; *head && (*head)->priority <= newnode->priority; head = &(*head)->next) {;} newnode->next = *head; *head = newnode; return; } 

…如果你不喜欢空循环,你可以添加一个if(...) break;


 void insert(struct node **head, int data, int priority){ struct node *newnode = getnewnode(data, priority); for( ; *head ; head = &(*head)->next) { if( (*head)->priority > newnode->priority) break; } newnode->next = *head; *head = newnode; return; }