您的位置:首页 > 编程语言 > C语言/C++

Partition List

2016-07-24 10:29 459 查看
题目描述:

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
.
解题思路:
模仿快排的一次排序过程即可。

注:在链表的开头加一个虚拟的节点(dummyHead)可以简化处理过程。

AC代码如下:

class Solution {
public:
ListNode* partition(ListNode* head, int x) {
if (head == NULL) return NULL;
ListNode* dummyHead1 = new ListNode(-1);
ListNode* p = dummyHead1;
ListNode* dummyHead2 = new ListNode(-1);
dummyHead2->next = head;
ListNode* q = dummyHead2;
while (q->next != NULL){
if (q->next->val < x){
ListNode* tmp = q->next;
q->next = tmp->next;
p->next = tmp;
p = p->next;
}
else{
q = q->next;
}
}
p->next = dummyHead2->next;
return dummyHead1->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息