/**主要思想就是将原来的链表拆成2个,一个全部小于阈值,一个大于或者等于阈值,然后将后者链接到前者后面;
* 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 == NULL)
return NULL;
ListNode*s = new ListNode(0),*q=new ListNode(0);
ListNode *p=s,*r=q;
while (head!= NULL)
{
if (head->val < x)
{
s->next = head;
s = s->next;
}
else
{
q->next = head;
q = q->next;
}
head = head->next;
}
q->next = NULL;
s->next = r->next;
delete r;
return p->next;
}
};
86. Partition List
最新推荐文章于 2024-09-25 11:53:45 发布