Difficulty: Medium, Asked-in: Facebook, Microsoft, Amazon, Adobe, Yahoo.
Key takeaway: An excellent problem to learn problem-solving using iteration and recursion.
Given a singly linked list, write a program to swap every two adjacent nodes and return its head. If the number of nodes is odd, then we need to pair-wise swap all the elements except the last element.
Input: 12->42->9->30->56->20->NULL
Output: 42->12->30->9->20->56->NULL
Input: 1->2->3->4->5->NULL
Output: 2->1->4->3->5->NULL
The idea is to traverse the linked list linearly, pick the nodes in pairs and swap their links. By the end of the process, return the head pointer of the modified list. The idea looks simple, but we need to be careful with the pointer's movement.
Step 1: If the list is empty or contains only one node, no swaps are needed. We return head. Otherwise, proceed with pairwise swapping.
Step 2: After the first swap, the second node becomes the new head. We set newHead = head->next. Initialise curr = head and prev = NULL.
Step 3: While curr and curr->next are not NULL, we swap the adjacent pair:
Step 4: After completing all pairwise swaps, return newHead.
Key observation: The prev pointer maintains the connection between consecutive swapped pairs.
pairWiseSwap(head)
if head == NULL OR head -> next == NULL
return head
curr = head
newHead = head -> next
prev = NULL
while curr != NULL AND curr -> next != NULL
first = curr
second = curr -> next
first -> next = second -> next
second -> next = first
if prev != NULL
prev -> next = second
prev = first
curr = first -> next
return newHeadWe are doing a single traversal of the linked list and performing pointer movement operations at each iteration. In other words, we are doing constant operations with each node in the linked list. So, time complexity = O(n), where n is the number of nodes. We are using constant extra space, so space complexity = O(1).
Here is another approach that uses a dummy node. The dummy node simplifies pointer initialisation and makes it easier to handle changes to the head of the list. Let’s see how this works.
If we keep track of the node before each pair, we can swap pairs iteratively. We use three pointers: prev points to the node before the pair, while first and second point to the two nodes being swapped. After swapping them, we update the pointers to move on to the next pair.
Here are the steps:
pairWiseSwap(head)
dummy = new ListNode(0)
dummy -> next = head
prev = dummy
while prev -> next != NULL AND prev -> next -> next != NULL
first = prev -> next
second = prev -> next -> next
// Swapping nodes
prev -> next = second
first -> next = second -> next
second -> next = first
// Move to the next pair
prev = first
head = dummy -> next
delete dummy
return headWe are doing a single traversal of the linked list. So, time complexity = O(n), where n is the number of nodes. We are using constant extra space, so space complexity = O(1).
Now a critical question is: Can we solve this problem using the solution of a smaller sub-problem i.e. using recursion? If yes, then what would be the recursive structure? Let's think!
Suppose there are n nodes in the linked list and we swap the first two nodes. Now the problem will get reduced to swapping the remaining n - 2 nodes in pairs. So the solution idea would be to swap the first two nodes and call the same function for the remaining list if there are more than two nodes in the list. By the end of the process, we should return the head of the modified linked list.
Recursive structure: Pair-wise swapping of linked list size of n = Swapping the first two nodes + Pair-wise swapping of the remaining linked list of size n - 2 recursively.
Base case: This occurs when the linked list contains a single node or no nodes. In this case, if (head == NULL || head->next == NULL), return head.
pairWiseSwap(head)
if head == NULL OR head -> next == NULL
return head
remainingListHead = head -> next -> next
newHead = head -> next
newHead -> next = head
head -> next = pairWiseSwap(remainingListHead)
return newHeadSuppose the total number of nodes in the linked list is n.
The space complexity depends on the size of the call stack which will be equal to the height of the recursion tree. There would be a total n/2 number of recursive calls till our recursion reach the base case, so the height of the recursion tree = n/2. For this, recursion will use a call stack of size n/2, so space complexity = O(n).
If you have any queries or feedback, please write us at contact@enjoyalgorithms.com.Enjoy learning, Enjoy coding, Enjoy algorithms!