If I enter the input for this code as 1 2 3 4 5
then Ctrl-D to end the program, it will print
0 --> 5 --> 4 --> 3 --> 2 -->
, which is strange. I tried following a tutorial for building a linked list but I think i've done it slightly wrong.
#include <stdio.h>
#include <stdlib.h>
struct list
{
int a;
struct list *next;
};
typedef struct list List;
int main (void)
{
List *start, *end;
end = (List*)malloc(sizeof(List));
end = NULL;
while(scanf("%d", &(start -> a )) == 1)
{
start = (List*)malloc(sizeof(List));
start -> next = end;
end = start;
}
end = start;
while(start)
{
printf("%d --> ", start -> a);
start = start -> next;
}
return 0;
}
- I realise I shouldn't cast the return of malloc and should be checking the return of scanf! This is merely test code to learn how to build linked lists.