/************************* * Example of a doubly linked list data structure in C * * mahoney@cs c_structures$ make node_list * gcc -march=athlon64 -O2 node_list.c -o node_list * mahoney@cs c_structures$ ./node_list * Here are some sizes: * sizeof(struct node) = 12 * sizeof(int) = 4 * sizeof(long) = 4 * sizeof(short) = 2 * sizeof(node_ptr) = 4 * * A doubly linked list data structure: * root = 0x804a008 * &(root->prev) = 0x804a008 * &(root->next) = 0x804a00c * &(root->value) = 0x804a010 * list = ( 0 @ 0x804a008, 1 @ 0x804a018, 2 @ 0x804a028, 3 @ 0x804a038, ) * * Jim Mahoney, Jan 26 2007 * $Id: node_list.c 9911 2007-01-28 22:40:45Z mahoney $ ******************/ #include #include // Here's an example of a self-referential data structure in C, // namely a node in a doubly-linked list (each node points to the // the previous and next nodes so we can move forwards or backwards). // First we define a new pointer type (a 'node_ptr'), and then // use that new type within the definition of the 'struct node' itself. typedef struct node *node_ptr; // typedef struct node { // struct { ; ... }; node_ptr prev; node_ptr next; int value; }; // 'new_node' creates a new node and return a pointer to it. // inputs: pointers to the previous and next node, and this one's value. // side effects: modifies the pointers in the nodes 'prev' and 'next'. // sample usage: node_ptr root = new_node(NULL, NULL, 0); node_ptr new_node(node_ptr prev, node_ptr next, int value){ node_ptr self; self = (node_ptr) malloc(sizeof(struct node)); self->next = next; self->prev = prev; self->value = value; if (prev){ prev->next = self; } if (next){ next->prev = self; } return self; } // Print the value and pointer address of a node and the nodes that follow it. void print_list(node_ptr node){ printf(" list = ( "); while (node){ printf("%i @ %p, ", node->value, node); node = node->next; } printf(")\n"); } // Print various information about the sizes of things. void print_info(){ printf("Here are some sizes: \n"); printf(" sizeof(struct node) = %i\n", sizeof(struct node)); printf(" sizeof(int) = %i\n", sizeof(int)); printf(" sizeof(long) = %i\n", sizeof(long)); printf(" sizeof(short) = %i\n", sizeof(short)); printf(" sizeof(node_ptr) = %i\n", sizeof(node_ptr)); printf("\n"); } int main(){ int i, n_nodes; node_ptr root, tail; print_info(); root = new_node(NULL, NULL, 0); printf("An empty node :\n"); printf(" root = %p\n", root); printf(" root->prev = %p\n", root->prev); printf(" root->next = %p\n", root->next); printf(" root->value = %i\n", root->value); tail = root; n_nodes = 4; for (i=1; i