2012-08-16 79 views
0

我试图用C.打印链接列表,但是当我执行我的./a.out时它打印出空白。有人可以帮我解决我做错的地方。谢谢。在C中打印链接列表

#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; 
} 
+1

您的测试输入是什么? – timrau 2012-08-16 16:55:08

+0

当插入代理开始设置最后。 – BLUEPIXY 2012-08-16 16:58:30

回答

5

当你插入一个元素,您将start指针NULL前的一个。因此,只要你想打印清单,start->next就是NULL,并且不能打印任何东西。

您应该使用temp,而不是两个元素插入和列表输出。在记录清单之前,请记住将temp指向start

+2

XD击败了我1分钟 – 2012-08-16 17:00:21

+1

除了打印时,从未将'temp'设置为'start'可能会更好。这样他总是有一个指向列表的开始和结束的指针。 – 2012-08-16 17:02:40