Explain how to implement doubly linked lists using only one pointer value np[x] per item instead of the usual two (next and prev). Assume that all pointer values can be interpreted as k-bit integers, and def ine np[x] to be np[x] = next[x] XOR prev[x], the k-bit “exclusive-or” ofnext[x] and prev[x]. (The value NIL is represented by 0.) Be sure to describe what information is needed to access the head of the list. Show how to implement the SEARCH, INSERT, and DELETE operations on such a list. Also show how to reverse such a list in O(1) time.
Source: CLRS 10.2-8 of Cormen Third Edition
PS: This is not a homework question. I am practicing/revising data structures.
Refer the pointer as a ‘regular’ integer. So, you can do any integer operations on it, including xor.
For each node, store
xorValue = next ^ previous.Why is it helpful?
If you are iterating from front to end – you know where
previousis, and you have its value, so you can get next withnext = xorValue ^ previous.Same idea applies when iterating from last to first:
previous = xorValue ^ next.This is enough since you cannot reach any place in the linked list without iterating from last to first or first to last – so the value of
previousORnextis known to you, and as we have seen – it is all you need in order to get the other one.Based on this you can create (c-like Pseudo code):
For the head/last elements – regard the previous/next value (correspondingly) as simply NULL (0), and store the next element as it is. It works since
next ^ 0 = next