Simple Java Iterative and Recursive solutions


  • 0
    K
    public ListNode swapPairs(ListNode h) {
       if(h == null || h.next == null) return h;
       ListNode first = h.next;
       ListNode tmp = h.next.next;
       first.next = h;
       h.next = swapPairs(tmp);
       return first;
    }
    public ListNode swapPairs(ListNode h) {
        if(h == null || h.next == null) return h;
        ListNode tmp;
        ListNode newH = h.next;
        while(h.next != null){
            tmp = h.next.next;
            if(tmp == null || tmp.next == null){
                h.next.next = h;
                h.next = tmp;
                if(tmp != null) h = h.next;
            }else{
                h.next.next = h;
                h.next = tmp.next;
                h = tmp;
            }
        }
        return newH;
    }

Log in to reply
 

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