/**
* 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* p=new ListNode(INT_MIN);//create a new head before head
p->next=head;
head=p;
ListNode* curr=head;
ListNode* q=NULL;
while(curr->next)
{
if(curr->next->val>=x&&curr->val<x)//mark the partition point with q
{
q=curr;
curr=curr->next;
}
else if(curr->next->val<x&&q)//find the node needed to be moved after q
{
ListNode* move=curr->next;
curr->next=move->next;
move->next=q->next;
q->next=move;
q=move;
}
else
curr=curr->next;
}
q=head;
head=head->next;
delete q;
return head;
}
};
leetcode 86: Partition List
最新推荐文章于 2020-01-28 10:46:06 发布