Can’t seem to work out why I’m getting garbage output from this Linked List structure when I print the contents.
My goal is to add anything to the list, some string, char by char, an it should print it out in reverse. The reason Im using the extra Struct for Head + Tail is so that I can then print out the the order lines were entered in reverse as well.
typedef struct List {
char c;
struct List *next;
}List;
typedef struct {
List *head;
List *tail;
}FullList;
List* InsertList(int hd, List* t1) {
List *t = (List*)calloc(1,sizeof(List));
t->c = hd;
t->next = t1;
return t;
}
FullList addToStart(FullList c, char element) {
if (c.head == NULL) {
c.head = c.tail = InsertList(element, NULL);
}else {
c.head = InsertList(element, c.head);
}
return c;
}
int main(void) {
FullList InOrder;
FullList Reverse;
InOrder.head = NULL;
Reverse.head = NULL;
char c;
while ((c = getchar() != '.')) {
InOrder = addToStart(InOrder, c);
}
while (InOrder.head->next != NULL) {
printf("%c", (InOrder.head->c));
InOrder.head = InOrder.head->next;
}
return 0;
}
The problem is here:
it should be:
because
!=has higher precedence than=.What you are doing in
while ((c = getchar() != '.'))is:getchar.c, so yourcwill be either0or1. And when you print the character with value1you see that weird looking char.Also note that the return type of getchar is
int, so you need to declare c as int.Also
should be:
else you prematurely terminate the loop without processing the last node.