JAVA O(n) constant space solution


  • 0
    O
    //O(n) constant extra space
        public static ListNode oddEvenList(ListNode head) {
            if(head == null || head.next == null){
                return head;
            }
            ListNode p1 = head; //odd half
            ListNode p2 = head.next; //even half
            ListNode m = p2;
            while(p2 != null && p2.next != null){
                p1.next = p2.next;
                p1 = p1.next;
                p2.next = p2.next.next;
                p2 = p2.next;
            }
            p1.next = m; // connect even half and odd half
            return head;
        }
    

Log in to reply
 

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