题目描述:
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 define np[x] to be np[x] = next[x] XOR prev[x], the k-bit "exclusive-or" of next[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.
代码实现:
#include <iostream>
#include <cassert>
using namespace std;
定义
The ptrdiff pointer field holds the difference between the pointer to the next node and
the pointer to the previous node. Pointer difference is captured by using exclusive OR.
typedef struct Node
{
int elm;
struct Node* ptrdiff;
}listNode,*plistNode;
链表头和链表尾
plistNode StartNode=NULL;
plistNode EndNode=NULL;
遍历:向前还是向后取决于传进去的pre是在current的哪侧
plistNode NextNode(plistNode current,plistNode pre)
{
return (plistNode)((int)current->ptrdiff^(int)pre);
}
插入:在指定元素后插入,未找到则不插入
void InsertAfter(plistNode pNew,int Elem)
{
plistNode pre,next,current;
pre=NULL;
next=NULL;
current=StartNode;
while(current)
{
next=NextNode(current,pre);
if(current->elm==Elem)
{
next
if(next)
{
next->ptrdiff=(plistNode)((int)next->ptrdiff ^ /
(int)current ^ (int)pNew);
}
current
current->ptrdiff=(plistNode)((int)current->ptrdiff ^ /
(int)next ^ (int)pNew);
pNew
pNew->ptrdiff=(plistNode)((int)current ^ (int)next);
}
pre = current;
current =next;
}
}
void Insert(int Elem)
{
plistNode pNew = (plistNode)malloc(sizeof(listNode) );
if (! pNew) {
cout<<"malloc failed!/n";
return;
}
pNew->elm = Elem;
pNew->ptrdiff = NULL;
if ( !StartNode ) {
StartNode = EndNode = pNew;
}else {
InsertAfter( pNew, EndNode->elm);
EndNode = pNew;
}
}
root为StartNode则forward travel,若EndNode则backward travel
void TravelPrint(plistNode root)
{
plistNode pre=NULL;
plistNode current=root;
plistNode next;
while(current)
{
cout<<current->elm<<"/t";
next=NextNode(current,pre);
pre=current;
current=next;
}
}
int main()
{
plistNode current;
plistNode pNew;
for(int i=0;i<5;i++)
{
Insert(i);
}
cout<<"forward travel:/n";
TravelPrint(StartNode);
cout<<endl;
cout<<"backward travel:/n";
TravelPrint(EndNode);
cout<<endl;
system("pause");
return 0;
}