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.
解题思路:
思路很清晰,遍历一遍就可以完成。先找到指针的第一个插入位置(第一个大于x的节点的前一个节点),然后在该节点后将比x小的节点依次插入。
注意:可能会存在{2,1},x=2这样的情况,即节点要插入在head之前。为了统一处理,在链表前面加入一个值为INT_MIN的附加头结点。在处理结束后将该节点摘掉。注意指针内存的释放和悬垂指针的处理。
运行时间为8ms,代码如下:
/**
* 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 == NULL || head->next == NULL)
return head;
//preHead: additional head
ListNode *preHead = new ListNode(INT_MIN);
preHead->next = head;
head = preHead;
//part: the position before the insert node
ListNode *part(head);
while(part->next != NULL && part->next->val < x) {
part = part->next;
}
if(part->next == NULL) {
head = head->next;
preHead->next = NULL;
delete preHead;
preHead = NULL;
return head;
}
//pre: pre-node of p
ListNode *p(part->next), *pre(part);
while(p != NULL) {
if(p->val >= x) {
p = p->next;
pre = pre->next;
}
else {
pre->next = p->next;
p->next = part->next;
part->next = p;
p = pre->next;
part = part->next;
}
}
head = head->next;
preHead->next = NULL;
delete preHead;
preHead = NULL;
return head;
}
};