LeetCode 75

Odd Even Linked List

Problem
LC 328
Topic
Linked List
File
official75_LC328OddEvenLinkedList.java
Path
pkg5leetcode/official75/official75_LC328OddEvenLinkedList.java
Package
pkg5leetcode.official75
Command
java pkg5leetcode/official75/official75_LC328OddEvenLinkedList.java
Approach
Two chains for odd/even indices then connect.
Complexity
Time O(n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/official75/official75_LC328OddEvenLinkedList.java
1package pkg5leetcode.official75;2 3/*4 * Odd Even Linked List | LC 3285 * APPROACH: Two chains for odd/even indices then connect.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class official75_LC328OddEvenLinkedList {9    /** Same shape as pkg5leetcode/common/ListNode.java (nested for single-file runs). */10 11    static class ListNode {12        int val;13        ListNode next;14        ListNode(int val) { this.val = val; }15    }16 17    static ListNode oddEvenList(ListNode head) {18        if (head == null) return null;19        ListNode odd = head, even = head.next, evenHead = even;20        while (even != null && even.next != null) {21            odd.next = even.next;22            odd = odd.next;23            even.next = odd.next;24            even = even.next;25        }26        odd.next = evenHead;27        return head;28    }29 30    static int[] toArray(ListNode head) {31        java.util.List<Integer> list = new java.util.ArrayList<>();32        while (head != null) { list.add(head.val); head = head.next; }33        return list.stream().mapToInt(Integer::intValue).toArray();34    }35 36    public static void main(String[] args) {37        ListNode h = new ListNode(1); h.next = new ListNode(2); h.next.next = new ListNode(3);38        h.next.next.next = new ListNode(4); h.next.next.next.next = new ListNode(5);39        check(java.util.Arrays.equals(toArray(oddEvenList(h)), new int[]{1,3,5,2,4}), "case1");40        ListNode h2 = new ListNode(2); h2.next = new ListNode(1); h2.next.next = new ListNode(3);41        h2.next.next.next = new ListNode(5); h2.next.next.next.next = new ListNode(6);42        h2.next.next.next.next.next = new ListNode(4); h2.next.next.next.next.next.next = new ListNode(7);43        check(java.util.Arrays.equals(toArray(oddEvenList(h2)), new int[]{2,3,6,7,1,5,4}), "case2");44        System.out.println("all tests passed");45    }46 47    static void check(boolean cond, String name) {48        if (!cond) throw new AssertionError("FAILED: " + name);49        System.out.println("  PASS " + name);50    }51}