Simple Java O(n) Solution, using only one pointer


  • 0
    B
    public class Solution {
        public ListNode oddEvenList(ListNode head) {
            if (head == null || head.next == null){
                return head;
            }
            ListNode second = head.next;
            ListNode list = head;
            while (list.next != null && list.next.next != null){
                ListNode tmp = list.next;
                list.next = tmp.next;
                list = list.next;
                tmp.next = list.next;
                tmp = tmp.next;
            }
            list.next = second;
            return head;
        }
    }
    

Log in to reply
 

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