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;
};
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With