I adapted the @dkamins solution, in some way. Instead of pointing to a pointer, I return a new head . I also strengthened this.
struct Node { struct Node *next; int data; }; typedef struct Node * NodePtr; NodePtr swapEveryTwo(NodePtr head) { NodePtr newHead = (head && head->next) ? head->next : head; NodePtr n = head; while(n && n->next) { NodePtr tmp = n; // save (1) n = n->next; // (1) = (2) tmp->next = n->next; // point to the 3rd item n->next = tmp; // (2) = saved (1) n = tmp->next; // move to item 3 // important if there will be further swaps if(n && n->next) tmp->next = n->next; } // return the new head return newHead; }
In principle, the new list title is either the current head, if NULL , or the length is 1, or the second element.
In the swap cycle, tmp will eventually become the second element, but first it is the first. Therefore, we need to point to the 3rd element, which is the target of tmp->next = n->next; . I do not use a for loop, because if we did this, it would be less intuitive - the revaluation expression would only seem to jump 1 node per iteration. At the end of the loop while n = tmp->next; makes intuitive sense - we point it to the element after tmp , the second element.
The most important part is the last line. Since we are doing this in the forward direction, we must remember that the previous second iteration element will almost certainly point to the current iteration element 4th , because this iteration will replace 3 and 4 So, at the end of the iteration, if we understand that we will again change the next iteration, we calmly point the 2nd element to the current 4th element, knowing that the next iteration will be the 3rd element, and everything is true in the world.
For example, if list 2 -> 7 -> 3 -> 5 :
n = 2 tmp = 2 n = 7 tmp->next = 3 (2 -> 3) n->next = 2 (7 -> 2) n = 3 7 -> 2 -> 3 -> 5 but then there will be swaps, so the last statement says 7 -> 2 -> 5 3?
This is normal because n = 3, so we have not lost that node. Next iteration:
n = 3 tmp = 3 n = 5 tmp->next = NULL (3 -> NULL) n->next = 3 (5 -> 3) n = NULL
Answering the final answer 7 -> 2 -> 5 -> 3 .