mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 328. Odd Even Linked List.md
This commit is contained in:
parent
e3b2676b70
commit
00697e57dd
28
solutions/328. Odd Even Linked List.md
Normal file
28
solutions/328. Odd Even Linked List.md
Normal file
@ -0,0 +1,28 @@
|
||||
# [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;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
Loading…
Reference in New Issue
Block a user