Writing a function in C that represents an integer as a singly linked list, the minus sign for negative integers does not show up. What am I doing wrong? Can you suggest any improvements in the algorithm, and the fastest way to solve it? C noob here.
#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;
}
Since add_front returns the new head of the list, you have to do
The next problem is in your display function,
Will print the char as a number, printing the char
'-'as a number will not print a minus, but the value a-has, 43 in ascii.Either change the display function to do
Or store the actual character digit in your list, and print the elements with
printf("%c", head->info);. That is, instead of e.g. storing the number7in the list, you store the character digit'7'Which you can do with