Here's a simple linked list that counts from 0 to 9 with the root node being -1. It doesn't check for any errors, so keep that in mind:
Code:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int main ( void )
{
int x;
/* Declare all of the node pointers that we will
** need through the course of the program and
** allocate memory for the root node.
*/
struct node *iter, *whisker,
*root = malloc ( sizeof *root );
iter = root;
iter->data = -1, iter->next = NULL;
/* Populate the list by allocating memory for
** the current node's next pointer. This way
** we can then move iter to the next node easily.
*/
for ( x = 0; x < 10; x++ ) {
iter->next = malloc ( sizeof *iter );
iter = iter->next;
iter->data = x, iter->next = NULL;
}
/* Print the list with neato link symbols ^_^
*/
for ( iter = root; iter != NULL; iter = iter->next )
printf ( "%d %s", iter->data, ( iter->next != NULL ) ? "-> " : "\n" );
/* Free the allocated memory so that the system
** can now use it. The list has been created,
** used, and destroyed after this loop.
*/
for ( iter = root; iter != NULL; iter = whisker ) {
whisker = iter->next;
free ( iter );
}
/* When we're through tidying up after outselves,
** we can end the program.
*/
return 0;
}
-Prelude