您的位置:首页 > 其它

LeetCode: Partition List

2014-09-01 22:16 483 查看
[b]LeetCode: Partition List[/b]

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
.

地址:https://oj.leetcode.com/problems/partition-list/

算法:首先,找到第一个大于等于x的节点,记其前趋节点为pre,则在继续往后遍历,若发现比x小的值,则把该节点从链表中移出来,插入到pre节点后面。代码:

/**
* 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)   return NULL;
ListNode *p = head;
ListNode *pre = NULL;
while(p && p->val < x){
pre = p;
p = p->next;
}
if(!p)
return head;
ListNode *q = NULL;
while(p->next){
if(p->next->val < x){
q = p->next;
p->next = q->next;
if(pre){
q->next = pre->next;
pre->next = q;
pre = q;
}else{
q->next = head;
head = q;
pre = q;
}
}else{
p = p->next;
}
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: