#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int value; // 4 bytes
struct node *next; // 8 bytes
} node_t;
node_t *new_node(int v);
node_t *insert_node(node_t **head, int v);
void print_list(node_t *curr);
int main(int argc, char *argv[])
{
node_t *head = NULL;
int x;
// Keep reading integers, insert them into linked list
while(scanf("%d", &x) == 1) {
if(insert_node(&head, x) == NULL) {
exit(1);
}
}
// Print the list
print_list(head);
return 0;
}
// Creates and returns a new node with value v
node_t *new_node(int v)
{
node_t *n = NULL;
n = (node_t *)malloc(sizeof(node_t));
if(n == NULL) {
fprintf(stderr, "Error: malloc failed.\n");
return NULL;
}
// Set the value and next variables of n
n->value = v;
n->next = NULL;
return n;
}
// Inserts a node in the list beginning with head, returns
// a pointer to the new node. Note: We have to pass the address
// of head to this function so the value of head can be changed in
// the calling function.
node_t *insert_node(node_t **head, int v)
{
node_t *tmp = new_node(v);
if(tmp == NULL) return NULL;
if(*head == NULL) {
// case 1
*head = tmp;
} else {
// case 2
tmp->next = *head;
*head = tmp;
}
return tmp;
}
// Prints the list recursively
void print_list(node_t *curr)
{
if(!curr) return;
printf("Node address: %p\n", curr);
printf(" Node value: %d\n", curr->value);
printf("Next address: %p\n\n", curr->next);
print_list(curr->next);
}