在链表的末尾插入节点时,我的代码正在无限循环中运行。
IDE使用的Eclipse64位操作系统
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int info;
struct Node *next;
}node;
node *head;
node *ptr1;
void insert(int x);
void show();
int main()
{
int i,x,n;
puts("Enter number of elementsn");
scanf("%d",&n);
for(i=0;i<n;i++)
{
puts("Enter elements");
scanf("%d",&x);
insert(x);
}
show();
return 0;
}
//在链接列表中插入数据
void insert(int x)
{
node *ptr;
ptr1=head;
ptr=(node*)malloc(sizeof(node));
ptr->info=x;
if(head==NULL)
{
ptr->next=head;
head=ptr;
}
else
{
ptr1->next=NULL;
ptr1=ptr;
}
}
//打印列表的详细信息//无法计算此功能
void show()
{
while(ptr1->next!=NULL)
{
printf("%dn",ptr1->info);
ptr1=ptr1->next;
}
}
每次代码进入插入函数时,ptr1都设置为head,然后在else小节中将其设置为ptr,但不指向任何以前的项。这里有一个例子,以备不时之需。
typedef struct Node
{
int info;
struct Node *next;
}node;
node *head = NULL;
void insert(int x);
void show();
int main()
{
int i,x,n;
puts("Enter number of elementsn");
scanf("%d",&n);
for(i=0;i<n;i++)
{
puts("Enter elements");
scanf("%d",&x);
insert(x);
}
show();
return 0;
}
void insert(int x)
{
node *ptr = (node*)malloc(sizeof(node));
ptr->info=x;
ptr->next=head; /* this will always add the new entry at the beginning of the list all you need it to initialize the head to NULL*/
head = ptr; /* move the head so that it points to the newly created list element */
}
void show()
{
node *ptr1 = head;
printf("%dn",ptr1->info); /* print the head */
while(ptr1->next!=NULL) /* now walk the list remember it first looks if the next pointer in the list is null first then it jumps on next element in case it is not*/
{
ptr1=ptr1->next;
printf("%dn",ptr1->info);
}
}
记得在退出main之前创建一个函数来释放列表元素。
您的两个函数可以简化。单链表很容易实现。我还想通过将列表指针作为参数来改进函数,在insert()
的情况下,返回列表的新头:但首先让它工作!请注意,当全局变量的唯一用途是函数的局部变量时,没有理由或需要声明全局变量。
// insert new node at head of the list
void insert(int x) {
node *ptr = malloc(sizeof(node));
if (ptr == NULL) {
printf ("malloc failuren");
exit (1);
}
ptr->info = x;
ptr->next = head; // append existing list
head = ptr; // new head of list
}
// show the linked list
void show() {
node *ptr = head; // start at head of list
while (ptr != NULL) {
printf("%dn", ptr->info);
ptr = ptr->next; // follow the link chain
}
}
编辑这里是要添加到链接列表尾部的代码
// insert new node at tail of the list
void insert2(int x) {
node *tail = head;
node **last = &head;
node *ptr;
while (tail) {
last = &tail->next;
tail = tail->next;
}
ptr = malloc(sizeof(node));
if (ptr == NULL) {
printf ("malloc failuren");
exit (1);
}
ptr->info = x;
ptr->next = NULL;
*last = ptr;
}