/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
//1 find out the first node K,which is bigger than x
//2 remove the nodes behind K,which is smaller than x
//3 And insert them front of K one by one
if(head==NULL)
return head;
ListNode *dummy=new ListNode(0);
dummy->next=head;
ListNode *preCur=dummy;
ListNode *cur=dummy->next;
ListNode *preFast=dummy;
ListNode *fast=dummy->next;
while(cur!=NULL)//1
{
if(cur->val<x)
{
preCur=preCur->next;
cur=cur->next;
preFast=preFast->next;
fast=fast->next;
}
else
break;
}
while(fast!=NULL)//2
{
if(fast->val<x)//3
{
preCur->next=fast;
preFast->next=fast->next;
fast->next=cur;
preCur=preCur->next;
fast=preFast->next;
}
else
{
fast=fast->next;
preFast=preFast->next;
}
}
return dummy->next;
}
};
【leetcode】Partition List
最新推荐文章于 2019-07-16 09:33:43 发布