原题链接:Partition List
题解:
/**
* 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) {
/*
思路:类似与快排的partition过程,需要有两个指针分别指向小值和大值的末尾,小于就换位置,大于就下一个
Time Complexity:O(N)
Space Complexity:O(1)
*/
if(!head || !head->next)return head;
ListNode* res=new ListNode(0);
res->next=head;
ListNode* small=res,*max=NULL;
bool flag=false;
while(head){
if(head->val<x){
if(small->next==head){
small=head;
head=head->next;
}
else{
max->next=head->next;
head->next=small->next;
small->next=head;
small=head;
head=max->next;
}
}
else{
if(!flag){
max=head;
flag=true;
head=head->next;
}
else{
max=head;
head=head->next;
}
}
}
return res->next;
}
};