玩命加载中 . . .

328-奇偶链表


LeetCode 328. Odd Even Linked List

LeetCode-328

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.

Example 1:

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

method

把偶数位分离出来,最后再串在一起
注意奇数个和偶数个的结束条件判断

  • 奇数,even == nullptr
  • 偶数,even->next == nullptr
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;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录