Recursive way Java answer


  • 1
    M
    public ListNode swapPairs(ListNode head) {
        if( head == null || head.next == null ){
            return head;
        }
        ListNode p1 = head;
        ListNode p2 = p1.next;
        ListNode p3 = p2.next;
        
        p2.next = p1;
        p1.next = swapPairs(p3);
        
        head = p2;
        
        
        return head;
    }

Log in to reply
 

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