Suppose this is my XOR linked list struct...
struct xList {
int data;
xList* xor;
}
What should xor contain if the size of the xor linked list is 1 or 2?
Suppose this is my XOR linked list struct...
struct xList {
int data;
xList* xor;
}
What should xor contain if the size of the xor linked list is 1 or 2?
On
You store (previous ^ next) in the xorlink pointer.
Consider
struct xList
{
int data;
xList* xorlink;
}
A -> B -> C -> D
You start from the head. You know head doesn't have a previous - so xorlink will point to the B node. You save the current pointer(A) and move to next (B). You do (A ^ B->xorlink) to get the pointer to C. (B ^ C->xorlink) will give you the pointer to D. And so on
Reverse traversal is also similar.
Anyway, the answer to your question
It should contain
prev ^ nextwhereprevis a pointer to the previous element,nextis a pointer to the next element, and^is the XOR operator. The first element in the list obviously hasnilfor the previous item, and the last item hasnilfor the last item, so you'd getnil ^ nextandprev ^ nilfor those elements, respectively. In a list of size 1, there's no previous or next element, so you can probably figure out what you'd store in thexorfield.The idea with an xor linked list is that you have to know the address of either the previous or next element in the list already in order to determine the next or previous element. That's no problem if you're iterating through the list, though, and since that's what you do with linked lists, it can be a useful optimization. If you're iterating from head to tail, for example, you start with a pointer to the first element in the list. The previous element is
nil, so to get the next element you compute:next = prev ^ xor. You also have to remember the pointer to the current element before moving to the next element, so that you can use it to get to the following element.