gpt4 book ai didi

c - 每次从用户获取输入时,链表都会在末尾输入节点,但任何方法都会出现问题

转载 作者:行者123 更新时间:2023-11-30 16:58:41 25 4
gpt4 key购买 nike

当尝试在用户给出的每个输入的链表末尾附加节点时,此代码有问题。我不明白为什么会发生这种情况?有人可以指出问题是什么吗?如果有人知道,请建议我一些东西来修复这个错误?

#include <stdio.h>
//structure with two fields
struct node
{
int data;
struct node *next;

};
// data type definition
typedef struct node node;
//pointer to node which initially set to NULL
node *head=NULL;

//fucntion create and display
void create(int num);
void display();


main()
{
int n,i,num;

printf("enter the no of nodes : ");
scanf ("%d",&n);
for(i=0;i<n;++i)
{
printf("enter the data : ");
scanf("%d",&num);
create(num);

}
display();
}

//function create

void create(int num)
{
printf("\n");
if(head==NULL)
{
node *temp=(node*)malloc(sizeof(node));
temp->data=num;
temp->next=head;
head=temp;


}

else
{
node *temp1=head;
while(temp1!=NULL)
{
temp1=temp1->next;

}

node *ptr=(node*)malloc(sizeof(node));

ptr->data=num;
ptr->next=temp1->next;
temp1->next=ptr;


}

}

//function display()

void display()
{
node *temp;
temp=head;

printf("list is : ");
while(temp!=NULL)
{
printf("%d->",temp->data);
temp=temp->next;

}

}

最佳答案

这应该对你有帮助!

void create(int num)
{
printf("\n");
if(head==NULL)
{
node *temp=(node*)malloc(sizeof(node));
temp->data=num;
temp->next=head;
head=temp;


}

else
{
node *temp1=head;
//Modified the condition to traverse till the last node, not the end of it
while(temp1->next != NULL)
{
temp1=temp1->next;

}

node *ptr=(node*)malloc(sizeof(node));

ptr->data=num;
ptr->next=temp1->next;
temp1->next=ptr;


}

}

(注:程序可能还有其他问题,我没有运行过)

关于c - 每次从用户获取输入时,链表都会在末尾输入节点,但任何方法都会出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38621275/

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