Short java O(n) solution


  • 0
    H
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode cur = dummy;
        while(head!=null){
            ListNode tmp = head.next;
            if (tmp==null){
                cur.next = head;
                break;    
            }
            head.next = tmp.next;
            tmp.next = head;
            cur.next = tmp;
            cur = head;
            head = head.next;
        }
        return dummy.next;
    }

Log in to reply
 

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