思路:
1. 空間復雜度為 o(n) 解法. 創建兩個鏈表, 分別記錄大於 x 和小於 x 的節點, 最后合並
2. o(1) 的空間復雜度解法. 四個指針, 分別指向小於 x 部分鏈表的頭, 尾, 指向大於 x 部分鏈表的頭, 尾
總結:
1. 使用 dummyNode 減少判斷
代碼:
class Solution {
public:
ListNode *partition(ListNode *head, int x) {
ListNode *first, *second, *third, *fourth;
if(head == NULL)
return head;
ListNode *cursor = head;
ListNode *dummyNode = new ListNode(0);
dummyNode->next = head;
first = second = dummyNode;
while(cursor && cursor->val < x) {
second = cursor;
cursor = cursor->next;
}
if(cursor && cursor->val >= x) {
third = cursor;
fourth = cursor;
}
while(cursor) {
if(cursor->val < x) {
second->next = cursor;
fourth->next = cursor->next;
cursor->next = third;
second = cursor;
}else{
fourth = cursor;
}
cursor = cursor->next;
}
return dummyNode->next;
}
};
Update
較為簡潔的代碼
class Solution { public: ListNode *partition(ListNode *head, int x) { if(head == NULL) return head; ListNode *sm = new ListNode(0), *sm_tail = sm; ListNode *bg = new ListNode(0), *bg_tail = bg; ListNode *cur = head; while(cur) { if(cur->val < x) { sm_tail->next = cur; cur = cur->next; sm_tail = sm_tail->next; sm_tail->next = NULL; }else{ bg_tail->next = cur; bg_tail = bg_tail->next; cur = cur->next; bg_tail->next = NULL; } } sm_tail->next = bg->next; return sm->next; } };
