LeetCode - Swap Nodes in Pairs
Problem Link: https://leetcode.com/problems/swap-nodes-in-pairs/

Problem Description: Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list’s nodes. Only nodes itself may be changed.

Linked List — Data Structure

Approach Used: Recursion

Explanation: We have to readjust links of the linked list in such a way that every pair of adjacent nodes are swapped. Some things to keep in mind is that if there are at least two nodes then the new head node after all the swaps will always be the second node of the list or the next node of current head.

Now since it has to be done in pair we will always pick two nodes at a time, readjust the link and call the function again to do the same thing for rest of the nodes till we reach the base case.

The base case will be either the list is empty or has just 1 node in which case no operation can be done and we simply return the head.

Code: (Java)

public ListNode swapPairs(ListNode head) {

//base case

if(head==null || head.next==null)

return head;



//store the element we will send ahead (link to this node will be deleted in 2nd next step)

ListNode temp = head.next.next;



//new head will always be the second node of current list

ListNode newHead = head.next;



//link made from second node to first node (link to third node deleted)

head.next.next = head;



//call function again for rest of the nodes in list, first node will point to head of modified list

head.next = swapPairs(temp);



//return new head for every sublist and final original list

return newHead;

}

In case there any doubts, feel free to write it in the comments section. Thanks!
['Siddhant Jain']
['Leetcode', 'Data Structure Algorithm', 'Recursion', 'Linked Lists', 'Competetive Programming']