In-place method, just swap nodes


  • 0

    I misunderstood the meaning of in-place, I thought I am allowed to swap nodes.
    So I think of such method, just for praticing.
    1 2 3 4 5 - > 1 3 2 4 5 -> 1 3 5 2 4

    public ListNode oddEvenList(ListNode head) {
            if(head == null || head.next == null)   return head;
            ListNode pre = head;
            ListNode cur = head.next;
            while(cur != null && cur.next != null) {
                ListNode next = cur.next;
                cur.next = next.next;
                next.next = pre.next;
                pre.next = next;
                pre = pre.next;
                cur = cur.next;
            }
            return head;
        }
    

Log in to reply
 

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