LeetCode 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.
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;
}