请指出代码中的错误
函数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 emptyn");
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为空,因此您永远不会遇到p->next ==头的情况,并且您将始终处于循环中!
编辑:因此,解决方法是将其更改为:
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 emptyn");
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;
}
另一个版本,使用尾指针代替头指针,以便更快地追加。
#include <stdlib.h>
#include <stdio.h>
struct node {
struct node *next;
int data;
};
typedef struct node node;
node *insertatend(node *tail, int value)
{
node *p;
p = malloc(sizeof(node));
p->data = value;
if(tail == NULL){
p->next = p;
} else {
p->next = tail->next;
tail->next = p;
}
return p;
}
void display(node *tail)
{
node *p = tail;
if (p == NULL)
{
printf("nlinked list is emptyn");
return;
}
do{
p = p->next;
printf("%d ", p->data);
}while(p != tail);
printf("n");
}
int main()
{
node *tail = NULL;
int i;
for(i = 0; i < 8; i++)
tail = insertatend(tail, i);
display(tail);
return 0;
}