LeetCode 24. Swap Nodes in Pairs
2 min readJan 14, 2022
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example :
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Solution :
There are two approaches to solve this problem, one is iterative and the other is recursive.
We are going to solve using the Recursive approach.
We will take two nodes into consideration at a time and reverse them and then connect them with the rest of the pairwise reversed list recursively.
First, let’s look at the walkthrough of our code for the given example in the image given below:
Implementation :
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next ==null){
return head;
}
// Example : 1 --> 2 --> 3 --> 4
ListNode h = head, hn=head.next,u = head.next.next;
// h=1, hn=2, u=3
hn.next = h; // 2 --> 1
h.next = swapPairs(u); // 2 --> 1--> swapPairs(3)
return hn; //return 2
}
}
Runtime : 0ms
References:
- Geeks Practice Section
- Iterative Approach
Feel free to reach me out for any suggestion and queries, ping me on:
-[LinkedIn]
-[GitHub]
-[Twitter]