我的循环链表有问题。我相信问题出在我的显示功能上。请让我知道出了什么问题。我遇到的问题是显示前 n-1 个元素,然后出现分割错误(最后一个元素未显示,我得到分割错误(。谢谢 :-(
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* link;
};
struct Node* last = NULL;
void Insert_begin(int a)
{
struct Node* temp;
temp = malloc(sizeof(struct Node));
temp->data = a;
if (last == NULL)
last = temp;
else
{
temp->link = last->link;
last->link = temp;
}
}
void Display()
{
struct Node* temp;
if (last == NULL)
{
printf("list is empty");
}
temp = last->link;
while(temp!=last)
{
printf("%dn",temp->data);
temp = temp->link;
}
printf("%dn",temp->data);
}
int main()
{
Insert_begin(0);
Insert_begin(1);
Insert_begin(2);
Insert_begin(3);
Insert_begin(4);
Display();
return 0;
}
将第一个元素插入列表时,其链接必须指向自身:
if (last == NULL) {
last = temp;
last->link = last;
} else ...
在代码中,来自最后一个元素的链接未初始化。
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* link;
};
struct Node* last = NULL;
void Insert_begin(int a)
{
struct Node* temp;
temp = malloc(sizeof(struct Node));
temp->data = a;
if (last == NULL)
{
last = temp;
temp->link=last;//you forget this
}
else
{
temp->link = last->link;
last->link = temp;
last=temp;
}
}
void Display()
{
struct Node* temp;
if (last == NULL)
{
printf("list is empty");
return;
}
temp = last->link;
while(temp!=last)
{
printf("%dn",temp->data);
temp = temp->link;
}
printf("%dn",temp->data);
}
int main()
{
Insert_begin(0);
Insert_begin(1);
Insert_begin(2);
Insert_begin(3);
Insert_begin(4);
Display();
return 0;
}
if (last == NULL)
{
last = temp;
**// adding this line
last->link = last;**
}
解决问题
下面是更正的代码:
您犯的一个错误是在插入第一个值时,您没有将链接指向第一个节点本身。在循环单链表中,如果有一个节点,则链接(下一个(字段应指向该节点本身。
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node* link;
};
struct Node* last = NULL;
void Insert_begin(int a)
{
struct Node* temp;
temp = malloc(sizeof(struct Node));
temp->data = a;
if (last == NULL)
{
last = temp;
/*link field is pointing to that node
*it self(you have forgotten this)*/
last->link = temp;
}
else
{
temp->link = last->link;
last->link = temp;
}
}
void Display()
{
struct Node* temp;
if (last == NULL)
{
printf("list is empty");
}
temp = last->link;
while(temp!=last)
{
printf("%dn",temp->data);
temp = temp->link;
}
printf("%dn",temp->data);
}
int main()
{
Insert_begin(0);
Insert_begin(1);
Insert_begin(2);
Insert_begin(3);
Insert_begin(4);
Display();
return 0;
}
*
问题出在 Insert_begin(int a( 函数上,当你插入第一个节点时,你没有在旁边链接他的节点,所以下次插入第二个/第三个/.。节点,您尝试将第一个节点作为最后一个>链接访问,但它为您提供了垃圾值,这就是原因
void Insert_begin(int a)
{
struct Node* temp;
temp = malloc(sizeof(struct Node));
temp->data = a;
if (last == NULL)
{
last = temp;
last->link = last;
}
else
{
temp->link = last->link;
last->link = temp;
last = temp;
}
}
void Display()
{
struct Node* temp;
if (last == NULL)
{
printf("list is empty");
}
else
{
temp = last->link;
while(temp!=last);
{
printf("%dn",temp->data);
temp = temp->link;
}
printf("%dn",temp->data);
}
}
void main()
{
Insert_begin(10);
Insert_begin(20);
Insert_begin(30);
Display();
}