Created
December 8, 2014 12:10
-
-
Save twpayne/9760f8c3df02fb193904 to your computer and use it in GitHub Desktop.
Doubly-linked list with a single word per node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <assert.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| /* on Mac OS X sizeof(int) < sizeof(int *) so make sure we use a large enough integer! */ | |
| typedef int64_t integer_t; | |
| typedef struct { | |
| int value; | |
| integer_t nextprev; | |
| } node_t; | |
| /* allocate and initialize a new node */ | |
| node_t *new_node(int value) | |
| { | |
| node_t *n = malloc(sizeof(node_t)); | |
| assert(n != NULL); | |
| n->value = value; | |
| n->nextprev = 0; | |
| return n; | |
| } | |
| /* insert node at the head of the list and return the new head */ | |
| node_t *insert_at_head(node_t *head, node_t *n) | |
| { | |
| if (head == NULL) { | |
| n->nextprev = 0; | |
| } else { | |
| n->nextprev = (integer_t) head; | |
| head->nextprev ^= (integer_t) n; | |
| } | |
| return n; | |
| } | |
| /* print each value in the list */ | |
| void print_values(const char *prefix, node_t *n) | |
| { | |
| node_t *prev = NULL; | |
| while (n) { | |
| printf("%s: %d\n", prefix, n->value); | |
| node_t *tmp = n; | |
| n = (node_t *) (n->nextprev ^ (integer_t) prev); | |
| prev = tmp; | |
| } | |
| } | |
| int main(int argc, char *argv[]) | |
| { | |
| node_t *head = NULL; | |
| node_t *tail = NULL; | |
| /* create the first node, we always insert at the head so this node becomes the tail */ | |
| head = tail = insert_at_head(head, new_node(4)); | |
| /* insert a few more nodes */ | |
| head = insert_at_head(head, new_node(3)); | |
| head = insert_at_head(head, new_node(2)); | |
| head = insert_at_head(head, new_node(1)); | |
| /* iterate forward */ | |
| print_values("forward", head); | |
| /* iterate_backward */ | |
| print_values("backward", tail); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment