Linked lists, swap nodes

Here below is a function from a linked list problem. The proble prints out the link list: A B C D and the switchPlaces function swiches B and C so that the new lis prints out A C B D. I dont understand how the function works, can anyone explane.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
void switchPlaces(LinkNode* &thenode) {
    

    LinkNode* nodeC = thenode->next->next;
    LinkNode* nodeB = thenode->next;

    nodeB->next = nodeC->next;

    thenode->next = nodeC;

    nodeC->next = nodeB;



}
I'll try to explain, but someone else might be able to explain it more elegantly.
You should know what pointers are for this exercise. If you don't, I would start with something more simple before you get into linked lists.

You pass in thenode. This points to the first node of your linked list.
thenode->next is the 2nd node of the linked list.
thenode->next->next is the 3rd node of the linked list.

1
2
3
Linked List:
[ thenode ]  -->  [ thenode->next ]  -->  [ thenode->next->next ]  -->  [ nodeC->next ]
[    A    ]       [       B       ]       [          C          ]       [       D     ]

Note that on line 8, you are setting the value of nodeB->next, which is the same as nodeC, currently.
Also on line 8, you are accessing nodeC->next, which is the D node in your setup.


After line 8 runs, nodeB->next is now the same value as nodeC->next.
Or, in other words, nodeB's next is now node D.

1
2
3
Linked List:
[ thenode ]  -->  [ nodeB ]  -->  [ nodeC->next ]               [ nodeC ]  -->  [ nodeC->next ]
[    A    ]  -->  [   B   ]  -->  [      D      ]               [   C   ]  -->  [      D      ]


But now nothing is pointing to nodeC! And both nodeB and nodeC are pointing to node D.


Line 10: Let's partially fix it by relinking node A's next to be nodeC.

1
2
3
Linked List:
[ thenode ]  -->  [ nodeC ]  -->  [ nodeC->next ]            [ nodeB ]  -->  [ nodeB->next ]
[    A    ]  -->  [   C   ]  -->  [      D      ]            [   B   ]  -->  [      D      ]


But now... nothing is pointing to nodeB!


Line 12: Let's fix it by setting nodeC's next to nodeB.

1
2
3
Linked List:
[ thenode ]  -->  [ nodeC ]  -->  [ nodeB ]  -->  [ nodeB->next ]            
[    A    ]  -->  [   C   ]  -->  [   B   ]  -->  [      D      ]           


Now:
Node A's next is C.
Node C's next is B.
Node B's next is D.

C and B have been swapped, and every node's next correctly demonstrates this.



Caution: Your function will fail (invoke undefined behavior or a segfault) if thenode->next == nullptr
Last edited on
Topic archived. No new replies allowed.