简体   繁体   English

在 C 中打印整数的链表

[英]Printing a linked list of integers in C

I'm trying to get an integer of any size to a linked list in C. But when I print the list, a zero is printed always after the the integer.我正在尝试将任何大小的整数转换为 C 中的链接列表。但是当我打印列表时,总是在整数后面打印一个零。 Please note that I'm adding each digit of the integer to the head.(head has the 0th place of the integer)请注意,我将整数的每个数字添加到头部。(头部具有整数的第 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();
    }
}

when I input 123456, the output is 1234560. I tried to find solution, but couldn't.当我输入 123456 时,输出是 1234560。我试图找到解决方案,但找不到。 Please help请帮忙

You are one more node than necessary when you allocate to head1 .当您分配给head1时,您多一个节点。 You simply need to call the function get_number() as:您只需将函数get_number()调用为:

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

which would set the next of the last element (ie the first allocate node) to 0 and rest of the logic would be fine.这会将最后一个元素(即第一个分配节点)的next设置为0 ,其余的逻辑就可以了。

You also need to correctly call malloc() and change the type of c to int (to handle EOF ) as noted in the comments.您还需要正确调用malloc()并将c的类型更改为int (以处理EOF ),如注释中所述。 My preferred way is to allocate memory is:我的首选方法是分配内存:

TYPE *p = malloc(sizeof *p);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM