Recursion with explanation. Rotate and connect.


  • 0
    S
    public class Solution {
    public ListNode swapPairs(ListNode head) {
     //Base case  
     if(head == null || head.next == null)
            return head;
    //Rotate two nodes
        ListNode temp = head.next.next;
        head.next.next = head;
        head= head.next;
     //connect the second node to rest of the list. call recursion on third node from head  
     head.next.next = swapPairs(temp);
        
        return head;
    }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.