XOR linked list
XOR linked list 是为了解决双向链表两个指针占用空间的问题
XOR:异或,数学符号 “^”
XOR linked list 是将节点的previous 和 next 通过XOR算出结果保存在 npx(变量,起什么名字都无所谓)。这样就可以节省一个指针的空间,若果需要previous,previous = npx ^ next;
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<inttypes.h> 4 5 struct node{ 6 int data; 7 struct node * npx; 8 }; 9 10 struct node * XOR(struct node * pre, struct node * next) 11 { 12 return (struct node *)((uintptr_t)(pre) ^ (uintptr_t)(next)); 13 } 14 15 void insert(struct node ** head_ref, int data) 16 { 17 struct node * new_node = (struct node *)malloc(sizeof(struct node)); 18 new_node->data = data; 19 new_node->npx = XOR(NULL, (*head_ref)); 20 21 if(NULL != (*head_ref)) 22 { 23 struct node * next = XOR(NULL, (*head_ref)->npx); 24 (*head_ref)->npx = XOR(new_node, next); 25 } 26 27 (*head_ref) = new_node; 28 } 29 void printXORlinkedlist(struct node * head_ref) 30 { 31 struct node * current = head_ref; 32 struct node * pre = NULL; 33 struct node * next; 34 35 while(NULL != current) 36 { 37 printf("%d ", current->data); 38 39 next = XOR(current->npx, pre); 40 41 pre = current; 42 current = next; 43 } 44 } 45 int main(void) 46 { 47 struct node * head = NULL; 48 49 insert(&head, 0); 50 insert(&head, 1); 51 insert(&head, 2); 52 insert(&head, 3); 53 54 printXORlinkedlist(head); 55 return 0; 56 }
岁月如歌须静听