您的位置:首页 > 其它

Partition List

2014-07-12 13:39 337 查看
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
.

pro:给一个链表和一个基准值target,要求将链表partition,小于target的在左边,大于等于target的在右边,保持原链表中相对顺序不变。

sol:

1.新建一个root节点,指向head

2.定义pre,cur指针,用来遍历链表,定义less指针记录小于target的最后一个节点。less初始化为root。

3.遍历链表当发现小于target的节点就插入到less后,更新less。直到最后。

链表插入删除一定要熟练,其实也就没什么难的了。想清楚影响了几条线。对于单向链表,删除影响一条,插入影响两条。

code:

/**
* 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 *root = new ListNode(0);
root->next = head;
ListNode *less,*cur,*pre;
less = pre = root,cur = head;
bool flag = false;
while(cur!=NULL)
{

if(cur->val>=x)
{
pre = cur;
cur=cur->next;
flag=true;
}else
{
if(flag==false)
{
pre = cur;
less = cur;
cur = cur->next;

}else
{
pre->next = cur->next;
cur->next = less->next;
less->next = cur;
less = cur;
cur = pre->next;
}
}
}
return root->next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息