LeetCode/solutions/328. Odd Even Linked List.md
2019-12-04 13:50:50 +08:00

29 lines
1.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [328. Odd Even Linked List](https://leetcode.com/problems/odd-even-linked-list/)
# 思路
题给定一个链表,要重新排列链表,要求所有奇节点在前,偶节点在后。
我们可以用两个奇偶指针odd和even分别指向奇偶节点初始分别为`head`和`head->next`从前往后将奇节点和偶节点分别串起来。另外需要一个单独的指针even_head来保存偶节点的起点位置因为最后
需要将偶节点链表接在奇节点链表后。
# C++
```C++
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head) return head;
ListNode *odd = head, *even = head -> next, *even_head = even;
while(even && even -> next){
odd -> next = odd -> next -> next; // 将奇节点串起来
even -> next = even -> next -> next; // 将偶节点串起来
odd = odd -> next; // 工作指针右移
even = even -> next; // 工作指针右移
}
odd -> next = even_head;
return head;
}
};
```