Created
September 26, 2010 20:52
-
-
Save twpayne/598310 to your computer and use it in GitHub Desktop.
Doubly-linked list example using a single pointer per node
This file contains 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> | |
typedef struct { | |
int value; | |
long 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 = (long) head; | |
head->nextprev ^= (long) n; | |
} | |
return n; | |
} | |
/* print each value in the list */ | |
void print_values(node_t *n) | |
{ | |
node_t *prev = NULL; | |
while (n) { | |
printf(" %d", n->value); | |
node_t *tmp = n; | |
n = (node_t *) (n->nextprev ^ (long) 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 */ | |
printf("Forward:"); | |
print_values(head); | |
printf("\n"); | |
/* iterate_backward */ | |
printf("Backward:"); | |
print_values(tail); | |
printf("\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment