/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!head) return NULL;
ListNode *phead = NULL;
ListNode *qhead = NULL;
ListNode *pnode = NULL;
ListNode *qnode = NULL;
while (head) {
if (head->val < x) {
if (pnode) {
pnode->next = head;
pnode = head;
} else {
phead = pnode = head;
}
} else {
if (qnode) {
qnode->next = head;
qnode = head;
} else {
qhead = qnode = head;
}
}
head = head->next;
}
if (pnode) {
pnode->next = qhead;
}
if (qnode) {
qnode->next = NULL;
}
if (phead) return phead;
else return qhead;
}
};
Small Case: 8ms
Large Case: 40ms
Time: O(n)
Space: O(1)
看到这题就想了,死都不会忘记面G时那道神一般的链表快排... 亲们!惨痛的教训啊!