CLRS10.2-8练习 - 单指针值实现双向链表
要求:
Explain how to implement doubly linked lists using only one pointer value x.np per
item instead of the usual two (next and prev). Assume that all pointer values can be
interpreted as k-bit integers, and define x.np to be x.np = x.next XOR x.prev,
the k-bit “exclusive-or” of x.next and x.prev. (The value NIL is represented by 0.)
Be sure to describe what information you need 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.
解法:
x.np = x.prev ^ x.next
NIL用0表示
考虑链表第一个元素x.np = NIL ^ x.next = x.next,即链表头存的指针值和普通双向链表的next指针相同
中间所有元素x.np = x.prev ^ x.next
考虑链表最后一个元素x.np = x.prev ^ NIL = x.prev,即链表最后一个元素存的指针和普通双向链表的prev指针相同
我们知道第一个元素的next指针,中间元素的next指针可以通过前一个元素的np和当前元素的np异或计算获得,这就为前序遍历创造了可能
我们知道最后一个元素的prev指针,中间元素的prev指针可以通过当前元素的np和后一个元素的np异或计算获得,这就为后续遍历创造了可能
总之,np = prev ^ next, NIL = 0致使链表头元素和尾元素np值具有了特殊性,这正是此种表示的精妙之处,节省了O(n)的空间开销,但增加了运算开销(位运算),计算机执行位运算具有速度优势。
此种情况下,如果想要翻转链表就变得异常容易,只需要将链表的头尾指针交换即可。