指针在 C 中的插入中未修改



优先级队列的程序,我对指针有疑问,我正在传递头到插入,但它没有在插入中修改,如您所见,我正在打印头部

  • 在插入和主
  • 在插入中,它正在打印非零的东西
  • 在头部它是零
#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* 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=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);
}

没有任何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;
}

insert中的head是函数insert局部的,对它的任何修改都不会影响 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);

相关内容

  • 没有找到相关文章

最新更新