Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 328. Odd Even Linked List

Rain Hu

328. Odd Even Linked List


一、題目

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.
The first node is considered odd, and the second node is even, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in O(1) extra space complexity and O(n) time complexity.

Example 1:
oddeven1

Example 2: oddeven2

Constraints:


二、分析

三、解題

1. Linked List

ListNode* oddEvenList(ListNode* head) {
    if (!head) return NULL;
    ListNode* head2 = head->next;
    ListNode* odd = head;
    ListNode* even = head2;
    while (even && even->next) {
        odd->next = odd->next->next;
        even->next = even->next->next;
        odd = odd->next;
        even = even->next;
    }
    odd->next = head2;
    return head;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 938. Range Sum of BST
Next
[LeetCode] 2472. Maximum Number of Non-overlapping Palindrome Substrings