86. Partition List

ss
Apr 14, 2021

--

這題不難, 就是create兩條list然後, 大於等於目標值得就加到AList, 反之就加BList,

這題要注意的是, 如果你是直接把節點當作只到的對象, 在最後串起來的同時, 一定要讓AList的最後一個next指到 nullptr, 否則很有可能最後一個next其實是BList的值, 造成runtime error

/**
* 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 *t1 = new ListNode(-1);
ListNode *t2 = new ListNode(-1);
ListNode *t2_h = t2, *t1_h = t1;
while(head){
ListNode *t = head->next;

if(head->val >= x){
t2->next = head;
t2 = t2->next;
}else{
t1->next = head;
t1 = t1->next;
}
head = t;

}
t2->next = nullptr;
t1->next = t2_h->next;
return t1_h->next;
}

};

--

--

ss
ss

No responses yet