在C中打印链接列表

Tej*_*eja 0 c linked-list

我正在尝试使用C.打印链接列表.但是当我执行我的./a.out时,它会将我打印为空.有人可以帮我解决我做错的地方.谢谢.

#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;
}
Run Code Online (Sandbox Code Playgroud)

tim*_*rau 5

无论何时插入元素,都可以将start指针移动到之前的指针NULL.因此,无论何时您想要打印列表,start->next都是NULL,并且无法打印任何内容.

您应该使用temp元素插入和列表输出.只需记住在走过列表之前再temp回过头来start.

  • XD打了我1分钟 (2认同)