簡體   English   中英

在 C 中打印整數的鏈表

[英]Printing a linked list of integers in C

我正在嘗試將任何大小的整數轉換為 C 中的鏈接列表。但是當我打印列表時,總是在整數后面打印一個零。 請注意,我將整數的每個數字添加到頭部。(頭部具有整數的第 0 位)

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int digit;
    struct node* next; 
};

void get_number(struct node** head);
int create_node(int digit, struct node** head);
void printlist(struct node* head);


int main()
{
    struct node* head1 = malloc(sizeof(struct node*));

    get_number(&head1);

    printlist(head1);

    return 0;   
}

int create_node(int digit, struct node** head)
{
    struct node* tmp = malloc(sizeof(struct node*));

    tmp -> digit = digit;
    tmp -> next = *head;

    *head = tmp;

}

void printlist(struct node* head)
{
    struct node* curr = head; 
    if(!head)
        return;

    while(curr != NULL )
    {
        printf("%d",curr -> digit);
        curr  = curr -> next;
    }
}   

void get_number(struct node** head)
{
    int k;
    char c;

    c = getchar();
    while(c != '\n' && c != ' ')
    {
        k = c - '0';
        create_node(k, head);
        c = getchar();
    }
}

當我輸入 123456 時,輸出是 1234560。我試圖找到解決方案,但找不到。 請幫忙

當您分配給head1時,您多一個節點。 您只需將函數get_number()調用為:

   struct node* head1 = 0;
   get_number(&head1);

這會將最后一個元素(即第一個分配節點)的next設置為0 ,其余的邏輯就可以了。

您還需要正確調用malloc()並將c的類型更改為int (以處理EOF ),如注釋中所述。 我的首選方法是分配內存:

TYPE *p = malloc(sizeof *p);

暫無
暫無

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

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