gpt4 book ai didi

c - 在循环链表的末尾插入在 C 中不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 08:23:39 25 4
gpt4 key购买 nike

请指出代码中的错误

insertatend() 函数第一次插入但不会再次插入。

我想在循环链表的末尾插入一个节点,但是在第一次插入一个元素后,如果我们再次尝试输入数据,它就会卡在 while 循环中。

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

typedef struct node node;
node *head = NULL;

node *insertatend(node *head, int value)
{
node *temp, *p;
p = head;
temp = (node *)malloc(sizeof(node));
temp->data = value;
temp->next = head;
if (head == NULL)
{
head = temp;
}
else
{
while (p->next != head)
p = p->next;
p->next = temp;
}
return head;
}

void display(node *head)
{
node *p = head;
if (head == NULL)
{
printf("\nlinked list is empty\n");
return;
}
while (p->next != head)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}

int main()
{
int ch = 1, value;
while (ch)
{
printf("1.Insert 2.Display");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("enter an element:");
scanf("%d", &value);
head = insertatend(head, value);
break;
case 2:
display(head);
break;
}
}
return 0;
}

最佳答案

我认为错误在这里:

temp->next=head;
if(head==NULL){
head=temp;
}

当您输入第一个元素时,head 为空。所以 temp->next 被设置为 NULL 并且 head 被设置为 temp。当您输入第二个元素时,它会执行以下操作:

else{
while(p->next!=head)
p=p->next;
p->next=temp;}

其中 p->next 为 null,因此您永远不会遇到 p->next == head 的情况,您将始终处于循环中!

编辑:所以解决方法是将其更改为:

if(head==NULL){
head=temp;
}
temp->next=head;

编辑:显示函数中的第二个错误:循环不打印最后一个元素。我刚刚测试了它并且工作正常。

所以完整的代码应该是这样的:

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

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

typedef struct node node;
node *head = NULL;

node *insertatend(node *head, int value)
{
node *temp, *p;
p = head;
temp = (node *)malloc(sizeof(node));
temp->data = value;

if (head == NULL)
{
head = temp;
}
else
{
while (p->next != head)
p = p->next;
p->next = temp;
}
temp->next = head;
return head;
}

void display(node *head)
{
node *p = head;
if (head == NULL)
{
printf("\nlinked list is empty\n");
return;
}
do
{
printf("%d ", p->data);
p = p->next;
} while (p != head);
printf("\n");
}

int main()
{
int ch = 1, value;
while (ch)
{
printf("1.Insert 2.Display");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("enter an element:");
scanf("%d", &value);
head = insertatend(head, value);
break;
case 2:
display(head);
break;
}
}
return 0;
}

关于c - 在循环链表的末尾插入在 C 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32167800/

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