less than 1 minute read

Problem Statement

leetcode problem link

My Solution [Accepted]

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int val=0, ListNode next=null) {
 *         this.val = val;
 *         this.next = next;
 *     }
 * }
 */
public class Solution {
    public ListNode OddEvenList(ListNode head) {
        if (head is null)
            return head;
        var sentinel = new ListNode(0, head);
        var curr = sentinel.next;
        var next = curr.next;
        ListNode second = next;
        var moveCurr = true;
        while (curr is not null && next is not null) {
            if (moveCurr) {
                curr.next = next.next;
                curr = curr.next;
            } else {
                next.next = curr.next;
                next = next.next;
            }
            moveCurr = !moveCurr;
        }

        curr = sentinel.next;
        while (curr.next is not null) {
            curr = curr.next;
        }

        curr.next = second;

        return sentinel.next;
    }
}

Editorial

public class Solution {
    public ListNode oddEvenList(ListNode head) {
        if (head == null) return null;
        ListNode odd = head, even = head.next, evenHead = even;
        while (even != null && even.next != null) {
            odd.next = even.next;
            odd = odd.next;
            even.next = odd.next;
            even = even.next;
        }
        odd.next = evenHead;
        return head;
    }
}