LeetCode 24. Swap Nodes in Pairs

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.)
Input: head = [1,2,3,4]
Output: [2,1,4,3]
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
}
}
Feel free to reach me out for any suggestion and queries, ping me on:
-[LinkedIn]
-[GitHub]
-[Twitter]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rohit Mittal

Rohit Mittal

I am an enthusiastic engineer, seeking an opportunity where I can explore, evolve, learn and at same time contribute to the goals of an organization.