您的位置:首页 > 其它

Leetcode_86_Partition List

2016-04-11 17:37 363 查看
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小,后半部分比x大,但是不允许改变链表原本的顺序。

思路:建两个空链表,一个放大的,一个放小的,然后最后把他们连起来就行了。

坑:连接的时候要把greater指针的next清空然后再用,less的next指向greater的头指针,否则容易出现死循环。

/**
* 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 *ans = getAns(head, x);
return ans;
}

ListNode* getAns(ListNode* head, int x)
{
ListNode *less_h = NULL;
ListNode *greater_h = NULL;
ListNode *less = NULL;
ListNode *greater = NULL;
ListNode *iter = head;
while(iter!=NULL)
{
if(iter->val<x)
{
if(less_h == NULL)
{
less_h = iter;
less = iter;
}
else
{
less->next = iter;
less = less->next;
}
}
else
{
if(greater_h == NULL)
{
greater_h = iter;
greater = iter;
}
else
{
greater->next = iter;
greater = greater->next;
}
}
iter = iter->next;
}
if(greater!=NULL) greater->next = NULL;
if(less_h == NULL) return greater_h;
else
{
less->next = greater_h;
return less_h;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode