gpt4 book ai didi

c - 如何更改代码以使输出等于节点中的所有数据元素?

转载 作者:行者123 更新时间:2023-11-30 14:53:47 25 4
gpt4 key购买 nike

我今天学习了链表并尝试了这段代码。我想使用 for 循环向列表输入 5 个值。在for循环的底部,“head = head->next”将头指针前进到列表中的下一个节点,当循环终止时,列表中最后一个节点的 .next 字段设置为 NULL 以标记列表的末尾,然后使用 while 循环输出列表。但是当我编译并运行代码时,列表的输出值并不相同!作为输入值。我哪里出错了?

    #include<stdio.h>
#include<stdlib.h>

struct node{
int data;
int key;
struct node* next;
};

struct node* head=NULL;


int main(){

int i;
int a;
int b;
head=(struct node*)malloc(sizeof(struct node));//allocated memory

for(i=0;i<5;i++){
scanf("%d %d",&a,&b);
head->data=a;
head->key=b;
head->next=(struct node*)malloc(sizeof(struct node));
head=head->next;
}
head->next=NULL;

int j;
struct node* m;
m=head;


while(m!=NULL){
printf("%d %d ",m->data,m->key);
m=m->next;

}

}

最佳答案

这是在链表末尾进行插入的方式:

void insertend(int a,int b)
{
current=head;
struct list * temp=(struct list*) malloc(sizeof(list));
temp->data=a;
temp->key=b;
temp->next=NULL;
while(current->next!=NULL)
current=current->next;
current->next=temp;
current=temp;
}

关于c - 如何更改代码以使输出等于节点中的所有数据元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47023596/

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