#define SWAP_PTRS(a, b) do { void *t = (a); (a) = (b); (b) = t; } while (0)
Node* MergeLists(Node* list1, Node* list2)
{
Node *list = NULL, **pnext = &list;
if (list2 == NULL)
return list1;
while (list1 != NULL)
{
if (list1->data > list2->data)
SWAP_PTRS(list1, list2);
*pnext = list1;
pnext = &list1->next;
list1 = *pnext;
}
*pnext = list2;
return list;
}
This code is from here, the chosen answer of this question.
I cannot understand 3 lines here:
*pnext = list1;
pnext = &list1->next;
list1 = *pnext;
Can anyone kindly help me? Explain it for me?
Edited: Can I change these 2 lines:
pnext = &list1->next;
list1 = *pnext;
to
list = list-> next;
From the start: You have two lists and a new list head which you will be returning. pnext points to that initially.
The code aims to do as few pointer reassignments as possible, so tries to keep the initial ‘next’ pointers of the input lists intact.
Swap is there to ensure that the smaller element is the first of list1. What those lines does is:
Going step by step:
Gets *pnext (which is list before the first iteration) to point to the node containing the smallest element:
.
Is the tricky part, as noted before & operator has low precedence. It’s also hard to display graphically for it actually looks into part of a Node construct. Something like this though:
where x is the next pointer of the o which list1 points to.
Advances the list1 head, as its first element is processed.
You have nothing to do with list from here on, for you want to return it as the head of the merged list.
The invariant there is pnext points to where the last processed element’s next points to, which is where the smallest element from list1-2 should go. The interesting stuff happens with swaps, try to work out the exact proceedings yourself (hard to draw like this, and good exercise to understand what ** does). I might add it if I find a good way to draw it.
You cannot use
list = list-> next;for it would do something like this:Which means you lose that lonely o (and everything else eventually as the loop progresses).
edit: The
*pnext = list2;at the end does this:Loop termination (state before the said statement):
After the statement:
That statement appends the remaining list to the end of the list. Then Node* list is returned, pointing to the head of the merged list.
edit2:
And all the way, pnext would be better represented like this:
Which means it points to the next pointer of the last processed node.