[英]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.