Share My Java solution


  • 0
    L
        public ListNode oddEvenList(ListNode head) {
            if (head == null || head.next == null || head.next.next == null) return head;
            ListNode evenHead = head.next;
            ListNode oddHead = head;
            ListNode even = evenHead;
            ListNode odd = oddHead;
            ListNode oddNext = null;
            ListNode evenNext = null;
            while(even != null && odd != null) {
                oddNext = odd.next.next;
                evenNext = even.next.next;
                odd.next = oddNext;
                even.next = evenNext;
                odd = oddNext;
                even = evenNext;
                if (even != null && even.next == null) {
                   odd.next = null; 
                   break;
                }
            }
            odd.next = evenHead;
            return head;
        }
    }
    

Log in to reply
 

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