[英]How do you display elements of the linked list, without going into a non terminating while loop?
我正在编写一个 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;
}
Output:输入数据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 ,此代码将起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.