如何解决如何在不进入非终止 while 循环的情况下显示链表的元素?
我正在编写 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,此代码将起作用
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。