Java Recursive Solution


  • 2

    Recursion is easy to understand but may be stack consuming and cause StackOverflowException when input is large. Need to be rewrite in iterative way.

    	public ListNode swapPairs(ListNode head) {
    		if (head == null)
    			return head;
    
    		ListNode first = head;
    		ListNode second = head.next;
    		if (second != null) {	// has pair node
    			first.next = second.next;
    			second.next = first;
    			first.next = swapPairs(first.next);
    			return second;
    		}
    		return first;
    	}
    

  • 0
    3

    @keZhenxu 可以把第二个判断提前,如下:

            public ListNode swapPairs(ListNode head) {
    		if (head == null || head.next == null) {
    			return head;
    		}
    		
    		ListNode second = head.next;
    		head.next = second.next;
    		second.next = head;
    		head.next = swapPairs(head.next);
    		return second;
    	}
    

Log in to reply
 

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