用 C 语言编写一个将整数表示为单链表的函数,负整数的减号不显示。我究竟做错了什么?你能建议算法的任何改进,以及解决它的最快方法吗?这里是菜鸟。
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char info;
struct Node *link;
} Node;
Node* add_front (Node* head, char info)
{
Node* t = malloc(sizeof(struct Node));
t->info = info;
t->link = head;
return t;
}
void display (Node* head)
{
while(head != NULL) {
printf("%d ", head->info);
head = head->link;
}
}
Node* number_list (int n)
{
int digit, minus = (n < 0 ? 1 : 0);
Node* list = NULL;
if (minus) n *= -1;
do {
digit = n % 10;
list = add_front(list, (char)digit);
n = n / 10;
} while(n > 0);
if (minus) add_front(list, '-');
return list;
}
int main()
{
int n = -1024;
Node* l = number_list(n);
display(l);
return 0;
}