O(n) Time + O(1) Space #Java


  • 0
    public class Solution {
        public ListNode oddEvenList(ListNode head) {
            if (head == null || head.next == null || head.next.next == null) return head;
            
            ListNode oddOrganized = head;
            ListNode evenOrganized = head.next;
            ListNode oddToMove = evenOrganized.next;
            
            while(oddToMove != null) {
                evenOrganized.next = oddToMove.next;
                oddToMove.next = oddOrganized.next;
                oddOrganized.next = oddToMove;
                
                evenOrganized = evenOrganized.next;
                oddOrganized = oddOrganized.next;
                if (evenOrganized == null) break;
                oddToMove = evenOrganized.next;
            }
            
            return head;
        }
    }
    

Log in to reply
 

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