---
title: 'LeetCode 328. Odd Even Linked List'
disqus: hackmd
---
# LeetCode 328. Odd Even Linked List
## Description
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

Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
## Constraints
The number of nodes in the linked list is in the range [0, 10^4^].
-10^6^ <= Node.val <= 10^6^
## Answer
此題就是將一個list分成兩個來接的概念,先將head->next暫存成ans,用來之後奇點接偶點所用。
這邊將head分成奇點opr1和偶點opr2,因為我們都要用到next點,所以while要檢查next點是否為NULL,不然指到NULL的next就會有問題。
進入while之後就是開始往下跳接,之後就下推,依序循環到底,最後再把偶點頭ans接上opr1,就可以return head為答案了。
```Cin=
struct ListNode* oddEvenList(struct ListNode* head){
if(head == NULL || head->next == NULL || head->next->next == NULL){return head;}
struct ListNode *ans = head->next, *opr1 = head, *opr2 = head->next;
while(opr1 != NULL && opr1->next != NULL && opr2 != NULL && opr2->next != NULL){
opr1->next = opr1->next->next;
opr2->next = opr2->next->next;
opr1 = opr1->next;
opr2 = opr2->next;
}
opr1->next = ans;
return head;
}
```
## Link
https://leetcode.com/problems/odd-even-linked-list/
###### tags: `Leetcode`