Java solutions, the first one do not use recursion, while the second one use recursion.


  • 0
    /* not recursion */
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode cur = head, pre = new ListNode(0);
        pre.next = head;
        head = pre;
        /* it maybe not easy to understand, you'd better draw a figure */
        while (cur != null && cur.next != null) {
         	pre.next = cur.next;
          	cur.next = pre.next.next;
           	pre.next.next = cur;
           	pre = cur;
           	cur = cur.next;
        }
        return head.next;
    }
    
    /* recursion */
    public ListNode swapPairs2(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode tmp = head.next;
        head.next = swapPairs(tmp.next);
        tmp.next = head;
        return tmp;
    }
    

Log in to reply
 

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