86. Partition List
1.問題
給予一個linked list以及數字x, 分割list: 小於x的要放在大於等於x的node之前

2.想法
提問
確認題意: 將輸入的兩個字串轉為數字相乘並返回對應的字串
function header, parameter
test input
說明想法
Create 2 lists
list 1用來保留小於x的node
list 2用來儲存大於等於x的node
最後將list2接到list 1後面
測試計算複雜度
3.程式碼
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if (!head) {
return NULL;
}
ListNode* tmp1 = new ListNode(0), *pre1 = tmp1;
ListNode* tmp2 = new ListNode(0), *pre2 = tmp2;
ListNode* curr = head;
while (curr) {
if (curr->val < x) {
pre1->next = curr;
pre1 = pre1->next;
curr = curr->next;
} else {
pre2->next = curr;
curr = curr->next;
pre2 = pre2->next;
pre2->next = NULL;
}
}
pre1->next = tmp2->next;
return tmp1->next;
}
};
Last updated