Skip to content

Instantly share code, notes, and snippets.

@peteb
Created April 27, 2012 13:05
Show Gist options
  • Save peteb/2509025 to your computer and use it in GitHub Desktop.
Save peteb/2509025 to your computer and use it in GitHub Desktop.
Double-linked list with just one link field. xor-trick.
#include <stdio.h>
#include <inttypes.h>
typedef struct node {
void *link;
int value;
} node_t;
#define LINK(prev, next) (void *)((uintptr_t)(prev) ^ (uintptr_t)(next))
void
iter(node_t *node) {
node_t *prev = 0;
while (node) {
printf("%d\n", node->value);
node_t *this_node = node;
node = (node_t *)((uintptr_t)prev ^ (uintptr_t)node->link);
prev = this_node;
}
}
int
main() {
node_t n1 = {0, 11};
node_t n2 = {0, 22};
node_t n3 = {0, 33};
node_t n4 = {0, 44};
n1.link = LINK(0, &n2);
n2.link = LINK(&n1, &n3);
n3.link = LINK(&n2, &n4);
n4.link = LINK(&n3, 0);
iter(&n1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment