In this lesson, we will continue with our linked list implementation and focus on how to swap two different nodes in a linked list. We will give different keys corresponding to the data elements in the nodes. Now we want to swap the two nodes that contain those two keys.
Singly Linked List: Node Swap
Swap Node B with Node D
1 of 2
Let’s go ahead and break down how we might go about solving this problem. One way to solve this is by iterating the linked list and keeping track of certain pieces of information that are going to be helpful.
Algorithm
We can start from the first node, i.e., the head node of the linked list and keep track of both the previous and the current node.
Singly Linked List: Node Swap
Swap Node B and Node C
1 of 7
In the above illustration, we first set the current node to the head of the linked list and the previous node to nothing because there’s no previous node to the current node. Next, we proceed through the linked list looking at the data elements and checking if the data element of the node that we’re on matches one of the two keys. If we find the match, we record that information and repeat the same process for the second key that we’re looking for. This is the general way we will keep track of the information.
There are two cases that we’ll have to cater for:
Node 1 and Node 2 are not head nodes.
Either Node 1 or Node 2 is a head node.
Implementation
Now let’s go ahead and write up some code that will allow us to loop through this linked list and keep track of both the current and previous node for the keys given to the method.