Skip to content
JZLeetCode
Go back

LeetCode 328 Odd Even Linked List

Table of contents

Open Table of contents

Description

Question Link: LeetCode 328

Given the head of a singly linked list, group the nodes at odd 1-based positions first, followed by the nodes at even 1-based positions. Preserve the original order inside both groups.

Example 1:

Input:  head = [1,2,3,4,5]
Output: [1,3,5,2,4]

Example 2:

Input:  head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]

Constraints:

Idea

Each node’s original 1-based position determines its group. Keep a tail for the odd-position chain and a tail for the even-position chain. Save the head of the even chain so it can be attached after the odd chain.

At each step, connect the odd tail to the next node, which is the next odd-position node. Then connect the even tail to the node after it and advance both tails. When no next odd node remains, append the even chain to the odd tail.

Input:  1 → 2 → 3 → 4 → 5 → null

Odd:    1 → 3 → 5
Even:   2 → 4

Result: 1 → 3 → 5 → 2 → 4 → null

The odd and even chains retain their input order because each node is appended to its group’s tail as we scan the list. Every link is updated a constant number of times.

Complexity: Time O(n)O(n), Space O(1)O(1).

Java

import struct.ListNode;

public final class OddEvenLinkedList {

    private OddEvenLinkedList() {
    }

    // O(n) time, O(1) extra space.
    public static ListNode oddEvenList(ListNode head) {
        if (head == null) {
            return null;
        }

        ListNode odd = head;
        ListNode evenHead = head.next;
        ListNode even = evenHead;
        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;
    }
}

Python

from typing import Optional

from algorithm.jzstruct.list_node import ListNode


class Solution:
    def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        """Group nodes by 1-based position with O(n) time and O(1) extra space."""
        if not head or not head.next:
            return head

        odd_tail = head
        even_head = even_tail = head.next
        while even_tail and even_tail.next:
            odd_tail.next = even_tail.next
            odd_tail = odd_tail.next
            even_tail.next = odd_tail.next
            even_tail = even_tail.next

        odd_tail.next = even_head
        return head

C++

#include "struct/ListNode.hpp"

class SolutionOddEvenLinkedList {
public:
    // O(n) time, O(1) extra space.
    ListNode* oddEvenList(ListNode* head) {
        if (!head) return head;

        ListNode* odd = head;
        ListNode* even = head->next;
        ListNode* evenHead = even;

        while (even && even->next) {
            odd->next = even->next;
            odd = odd->next;
            even->next = odd->next;
            even = even->next;
        }

        odd->next = evenHead;
        return head;
    }
};

Rust

use crate::list::list_node::ListNode;

pub struct Solution;

impl Solution {
    /// Group nodes by 1-based position in O(n) time and O(1) extra space.
    pub fn odd_even_list(mut head: Option<Box<ListNode>>) -> Option<Box<ListNode>> {
        let mut odd_head = None;
        let mut even_head = None;
        let mut odd_tail = &mut odd_head;
        let mut even_tail = &mut even_head;

        while let Some(mut odd_node) = head {
            head = odd_node.next.take();
            odd_tail = &mut odd_tail.insert(odd_node).next;

            let Some(mut even_node) = head else {
                break;
            };
            head = even_node.next.take();
            even_tail = &mut even_tail.insert(even_node).next;
        }

        *odd_tail = even_head;
        odd_head
    }
}
Share this post on:

Next Post
System Design - How AWS Lambda Reuses Execution Environments