Open fockspaces opened 1 year ago
有時候 recursion 不見得比較好解 這題需要準備雙指針分別往下指,接著讓終點的 odd node 指回 evenHead
/**
* 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) return NULL;
ListNode* evenHead = head->next;
ListNode* even = evenHead;
ListNode* odd = head;
while(even && even->next) {
odd->next = even->next;
even->next = odd->next->next;
odd = odd->next; even = even->next;
}
odd->next = evenHead;
return head;
}
};
https://leetcode.com/problems/odd-even-linked-list/description/