You can either add to a linked list at the head or the tail. You are doing it at the head. Let's look at how that works..., with input 3 1 4 1 5
Code:
NULL
3 -> NULL
1 -> 3 -> NULL
4 -> 1 -> 3 -> NULL
1 -> 4 -> 1 -> 3 -> NULL
5 -> 1 -> 4 -> 1 -> 3 -> NULL
Let's look at this running through your code real quick...
You are using head.next as the beginning of list which is... well, strange, but not a problem really...Okay, this creates the node, but we haven't told it where to point to yet.
Code:
t->next = head.next;
This little snippet tells the node that the node after it is the beginning of the list.And this snippet assigns the beginning of the list to point at the newly created node, so that every time you make a new node, you make it the first element in the list, and make what used to be the first element in the list the one after it... like in the picture.
Here is some code that adds to the end of the list...
Code:
#include <stdio.h>
#include <stdlib.h>
struct intlist {
int data;
struct intlist *next;
} ;
int main(void)
{
struct intlist head = { 0, 0 };
struct intlist *t;
int n;
t = &head;
while (scanf("%d",&n) == 1) {
t -> next = malloc(sizeof(struct intlist));
if (!t -> next) { fprintf(stderr,"fatal: out of memory\n"); exit(1); }
t = t -> next;
t -> data = n;
// Since t is the last element, the node after it is NULL
t -> next = NULL;
// head.next = t; Value of head needn't change.
}
for (t = head.next;t;t = t->next)
printf("%d\n",t->data);
exit(0);
}
Or you could just search for the end of the list every time you inserted a node, instead of keeping your pointer t always at the end of the list...
Code:
#include <stdio.h>
#include <stdlib.h>
struct intlist {
int data;
struct intlist *next;
} ;
int main(void)
{
struct intlist head = { 0, 0 };
struct intlist *t;
int n;
while (scanf("%d",&n) == 1) {
// This is really unneccisary, but it's helpful to know that this
// will run to the node such that t -> next == NULL
for (t = &head; t -> next != NULL; t = t -> next);
t -> next = malloc(sizeof(struct intlist));
if (!t -> next) { fprintf(stderr,"fatal: out of memory\n"); exit(1); }
t = t -> next;
t -> data = n;
// Since t is the last element, the node after it is NULL
t -> next = NULL;
// head.next = t; Value of head needn't change.
}
for (t = head.next;t;t = t->next)
printf("%d\n",t->data);
exit(0);
}