Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
基本思路:
1. 設置兩個臨時鏈表
2. 將小於x的節點,掛到一個鏈表上。將大於等於的節點,掛到另一個鏈表上。
3. 串接兩個鏈表。將後一個鏈表的頭部,掛以前一個鏈表的尾部。
所犯的錯誤:
初次提交時,漏寫了
p2->next = 0;提交後,報告運行時間超出。
/**
* 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) {
ListNode h1(0);
ListNode h2(0);
ListNode *p1 = &h1;
ListNode *p2 = &h2;
while (head) {
if (head->val < x) {
p1->next = head;
p1 = p1->next;
}
else {
p2->next = head;
p2 = p2->next;
}
head = head->next;
}
p1->next = h2.next;
p2->next = 0; // 此句漏寫,將會在單鏈表中產生環。
return h1.next;
}
};
在leetcode討論組中,有一個更簡潔的寫法。
https://leetcode.com/discuss/21032/very-concise-one-pass-solution
ListNode *partition(ListNode *head, int x) {
ListNode node1(0), node2(0);
ListNode *p1 = &node1, *p2 = &node2;
while (head) {
if (head->val < x)
p1 = p1->next = head;
else
p2 = p2->next = head;
head = head->next;
}
p2->next = NULL;
p1->next = node2.next;
return node1.next;
}