[英]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.