Java, 0ms, using recusion


  • 5
    Y
    public ListNode swapPairs(ListNode head) {
    	if(head == null || head.next == null)
    		return head;
    	
    	ListNode p1 = head, p2 = head.next, p3 = null;
    	p3 = p2.next;
    	p2.next = null;
    	p1.next.next = p1;
    	p1.next = p3;
    	
    	if(p3 != null)
    		p1.next = swapPairs(p3);
    	
    	return p2;
    }

  • -1
    Z

    i think we can remove line "p1.next.next = p1;"


  • 0
    M

    Swap can be done shorter. Thanks for the solution btw.

    ListNode p1 = head, p2 = head.next, p3 = head.next.next;
    p2.next = p1;
    p1.next = p3;


Log in to reply
 

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