Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a double linked list with only one pointer?

How to implement a double linked list with only one pointer?

It takes O(1) time to find the prev and next Node.

struct Node
{
   int val;
   Node* p;
};
like image 684
MainID Avatar asked Nov 18 '09 10:11

MainID


1 Answers

There is a classic hack: store the XOR of the 2 pointers (Prev and Next) and when traveling the list you always have 1 of those at hand (you just came from there) and you can XOR it with the stored value to get the other pointer.

Needless to say that this won't work in a GC environment.

like image 95
Henk Holterman Avatar answered Oct 11 '22 21:10

Henk Holterman