Simple java 1 ms iterative solution using modulus operator


  • 0
    M
    public class Solution {
        public ListNode oddEvenList(ListNode head) {
            if(head == null || head.next == null){
                return head;
            }
            
            ListNode curr = head;
            ListNode next = head.next;
            ListNode evenCopy = next;
            ListNode pointer = next.next;
            
            int num = 1;
            while(pointer !=null){
                if(num%2 != 0){
                    curr.next = pointer;
                    curr = curr.next;
                }
                else{
                    next.next = pointer;
                    next = next.next;
                }
                pointer = pointer.next;
                num++;
            }
            
            next.next = null;
            curr.next = evenCopy;
            return head;
        }
    }
    

Log in to reply
 

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