LeetCode 328. 奇偶链表(注意成环)
程序员文章站
2022-05-20 19:10:21
...
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head || !head->next) return head;
ListNode *p1 = head, *p2 = head->next;
ListNode *move1 = p1, *move2 = p2;
ListNode* cur = head->next->next;
int i = 2;
while(cur){
if(i&1){
move2->next = cur;
move2 = cur;
}else{
move1->next = cur;
move1 = cur;
}
cur = cur->next;
i++;
}
// 否则会成环的!
move2->next = nullptr;
move1->next = p2;
return p1;
}
};