ZhongKuo0228 / study

0 stars 0 forks source link

328. Odd Even Linked List #55

Open fockspaces opened 1 year ago

fockspaces commented 1 year ago

https://leetcode.com/problems/odd-even-linked-list/description/

fockspaces commented 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;
    }
};