在其中一位作者是Cormen的书中,有一个有趣的xor链表问题。
我把这个例子添加到xor链表中。
void insertAfter(plistNode pNew, T theElm)
{
plistNode pPrev, pCurrent, pNext;
pPrev = NULL;
pCurrent = pStart;
while (pCurrent) {
pNext = NextNode(pCurrent, pPrev);
if (pCurrent->elm == theElm) {
/* traversal is done */
if (pNext) {
/* fix the existing next node */
pNext->ptrdiff =
(plistNode) ((int) pNext->ptrdiff
^ (int) pCurrent
^ (int) pNew);
/* fix the current node */
pCurrent->ptrdiff =
(plistNode) ((int) pNew ^ (int) pNext
^ (int) pCurrent->ptrdiff);
/* fix the new node */
pNew->ptrdiff =
(plistNode) ((int) pCurrent
^ (int) pNext);
break;
}
pPrev = pCurrent;
pCurrent = pNext;
}
}
我不明白这段代码
pNext-> ptrdiff = (plistNode) ((int) pNext-> ptrdiff
^ (Int) pCurrent
^ (Int) pNew);
在我看来应该有像
这样的东西pNext-> ptrdiff = New Xor pNext[next]
感谢您的回答。对不起我的愚蠢问题,为什么在第一行使用了pNext-> ptrdiff
(pNext->ptrdiff = pNext->ptrdiff XOR pCurrent XOR pNew
)。乍一看,似乎pCurrent <====> pNew <====> pNext <====> (NextNode to pNext)
pCurrent与pNext-> ptrdiff
无关。
答案 0 :(得分:1)
A&lt; ===&gt; B&lt; ====&gt; C的XOR链接列表逻辑
B应包含A XOR C
现在,
1&gt;之前: pCurrent&lt; ====&gt; pNext&lt; ====&gt;(NextNode到pNext)
所以, pNext-&gt; ptrdiff = p当前XOR(NextNode到pNext)
2&gt;在pCurrent之后插入pNew后,您应该:
pCurrent&lt; ====&gt; pNew&lt; ====&gt; pNext&lt; ====&gt;(NextNode to pNext)
所以,pNext-&gt; ptrdiff应该是
pNext-&gt; ptrdiff = pNew XOR(NextNode to pNext)
所以代码是通过
实现的pNext->ptrdiff = pNext->ptrdiff XOR pCurrent XOR pNew
= pCurrent XOR (NextNode to pNext) XOR pCurrent XOR pNew [ replaced pNext->ptrdiff from 1 ]
= pCurrent XOR pCurrent XOR (NextNode to pNext) XOR pNew [ XOR is commutative ]
= 0 XOR (NextNode to pNext) XOR pNew [ A XOR A = NULL ]
= (NextNode to pNext) XOR pNew [ 0 XOR A = A ]
这是预期的[来自2]