https://leetcode-cn.com/problems/partition-list-lcci/
思路:这题做法也很多的,最蠢的应该就是排序了,我们来说以下线性复杂度的做法。搞一个 s m a l l small small链表把 < x <x <x的节点连接起来,再搞一个 b i g big big链表把 > = x >=x >=x的节点连接起来,然后把 s m a l l small small的尾部指向 b i g big big的头部,再把 b i g big big的尾部指向空即可。搞两个哨兵,方便操作。
/**
* 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) {
if(!head||!head->next)
return head;
ListNode small(0),big(0);//哨兵
ListNode *head1=&small,*head2=&big;
ListNode *cur=head;
while(cur){
if(cur->val<x)
head1->next=cur,head1=cur;
else
head2->next=cur,head2=cur;
cur=cur->next;
}
head2->next=nullptr;
head1->next=big.next;
return small.next;
}
};