gpt4 book ai didi

c - C 中插入时指针未修改

转载 作者:行者123 更新时间:2023-11-30 18:23:37 25 4
gpt4 key购买 nike

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

  • 在插入和主要
  • 在插入中打印一些非零的内容
  • 在 head 中它为零
    #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() 语句的 super 简化版本:

<小时/>
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 中插入时指针未修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52625172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com