簡體   English   中英

在C中打印鏈接列表

[英]Printing the linked list in C

我正在嘗試使用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;
}

無論何時插入元素,都將start指針移動到NULL之前的元素。 因此,每當您要打印列表時, start->nextNULL ,則什么也不能打印。

對於元素插入和列表輸出,應使用temp代替。 只要記住在遍歷列表之前將temp指向start即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM