Steward
分享是一種喜悅、更是一種幸福
程式語言 - LeetCode - C++ - 86. Partition List
題目:

解答:
/**
* 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* partition(ListNode* head, int x) {
ListNode d0;
ListNode d1;
ListNode *l = &d0;
ListNode *r = &d1;
while (head) {
if (head->val < x) {
l->next = head;
l = l->next;
}
else {
r->next = head;
r = r->next;
}
head = head->next;
}
r->next = nullptr;
l->next = d1.next;
return d0.next;
}
};