问题描述
我正在编写 C 代码,用于使用 while 循环实现和遍历链表。 我无法弄清楚我在代码中写错了什么。代码不是以 while (a!=NULL) 终止并显示链表中的所有元素,而是进入无限循环。这是代码.....
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node * next;
};
void display(struct node * a){
printf("The elements are :");
while(a!=NULL){
printf("%d\n",a->data);
a=a->next;
}
}
int main(){
int choice;
struct node * head,* new_node,* temp;
head = NULL; // head points to NULL
new_node=(struct node*)malloc(sizeof(struct node));
while(choice){
printf("Enter the Data");
scanf("%d",&new_node->data); // Entering value in new_node
new_node->next=NULL;
if (head == NULL)
{
head = temp = new_node;
}
else
{
temp->next = new_node;
temp = new_node;
}
printf("Enter 0 for ending and 1 for continuing");
scanf("%d",&choice);
}
display(head);
return 0;
}
输出: 输入数据1 输入 0 表示结束,输入 1 表示继续 1 输入数据 2 输入 0 表示结束,输入 1 表示继续 1 输入数据 3 输入 0 表示结束,输入 1 表示继续 0 3
3
3
3
3
3
3
......未终止
解决方法
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node * next;
};
void Display(struct node * a){
printf("The elements are :");
while(a!=NULL){
printf("%d\n",a->data);
a=a->next;
}
}
int main(){
int choice;
struct node * head,* temp;
head = NULL; // head points to NULL
while(choice){
struct node *new_node=(struct node*)malloc(sizeof(struct node));
printf("Enter the Data");
scanf("%d",&new_node->data); // Entering value in new_node
new_node->next=NULL;
if (head == NULL)
{
head = temp = new_node;
}
else
{
temp->next = new_node;
temp = new_node;
}
printf("Enter 0 for ending and 1 for continuing");
scanf("%d",&choice);
}
Display(head);
return 0;
}
根据Eugene Sh,此代码将起作用