[英]Printing the linked list in C
I am trying to print the linked list using C.But it is printing me empty when I execute my ./a.out. 我正在尝试使用C打印链接列表,但是当我执行./a.out时它却将我打印为空。 Can someone help me out where I am doing wrong.Thanks. 有人可以帮我解决我做错的地方。谢谢。
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
int main()
{
node *start,*temp;
start = (node *)malloc(sizeof(node));
temp = start;
temp -> next = NULL;
while(1)
{
int query;
printf("1.Insert\n");
printf("2.Print\n");
printf("Enter your choice:\n");
scanf("%d",&query);
if(query==1)
{
int data;
printf("Enter the element to be inserted.\n");
scanf("%d",&data);
while(start->next!=NULL)
{
start = start -> next;
}
start->next = (node *)malloc(sizeof(node));
start = start->next;
start->data = data;
start->next = NULL;
}
else if(query ==2)
{
printf("The list is as below:\n");
while(start->next!=NULL)
{
printf("%d \t",start->next->data);
start=start->next;
}
}
else
break;
}
return 0;
}
Whenever you insert an element, you move start
pointer to the one before NULL
. 无论何时插入元素,都将start
指针移动到NULL
之前的元素。 Thus, whenever you want to print the list, start->next
is NULL
, and nothing could be printed. 因此,每当您要打印列表时, start->next
为NULL
,则什么也不能打印。
You should use temp
instead for both element insertion and list output. 对于元素插入和列表输出,应使用temp
代替。 Just remember to point temp
back to start
before walking through the list. 只要记住在遍历列表之前将temp
指向start
即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.