我在列表末尾插入节点,但我的代码只打印第一个元素并在无限循环中运行。 我无法找出代码中的错误。
typedef struct nodetype
{
int info;
struct nodetype* next;
}node;
node *head=NULL;
void insertatend(int x);//x is the key element.
void print();
void insertatend(int x)
{
node *ptr;
ptr=(node*)malloc(sizeof(node));
ptr->info=x;
if(head==NULL)
{
ptr->next=ptr;
head=ptr;
}
else
ptr->next=ptr;
}
void print() //To print the list
{
node *temp=head;
printf("List is-");
while(temp!=NULL)
{
printf("%d",temp->info);
temp=temp->next;
}
}
最佳答案
考虑您的插入方法(我将在这里将 head 作为参数而不是全局参数)
void insertatend(node **hd, int x) {
node *ptr = NULL, *cur = NULL;
if (!(ptr = malloc(sizeof (node)))) {
return;
}
if (!*hd) {
*hd = ptr;
} else {
cur = *hd;
while (cur->next) {
cur = cur->next;
}
cur->next = ptr;
}
}
为了正确执行插入,您需要从头到尾遍历列表。 (因此上面函数中的 while
循环)。
关于c - 在链表末尾插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28498332/