Skip to content

328. Odd Even Linked List

class ListNode {
val: number;
next: ListNode | null;
constructor(val?: number, next?: ListNode | null) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
function oddEvenList(head: ListNode | null): ListNode | null {
if (!head?.next) {
return head;
}
let odd = head;
let even = head.next;
const evenHead = even;
while (even?.next) {
odd.next = even.next;
odd = odd.next;
even.next = odd.next;
even = even.next!;
}
odd.next = evenHead;
return head;
}
const first = new ListNode(1);
const second = new ListNode(2);
const third = new ListNode(3);
const fourth = new ListNode(4);
const fifth = new ListNode(5);
first.next = second;
second.next = third;
third.next = fourth;
fourth.next = fifth;
oddEvenList(first);