c/c++语言开发共享指针未在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; } 

      以上就是c/c++开发分享指针未在c中的insert中修改相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/522439.html

      (0)
      上一篇 2020年12月10日
      下一篇 2020年12月10日

      精彩推荐