【leetcode】Partition List

时间:2025-02-26 15:33:26

Partition List

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

最简答的,扫描两次链表
第一次找到所有比x小的节点,并保存下来
第二次找到所有比x大的节点,并保存下来
然后把他们两连起来
 /**
* 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=head;
ListNode *p0=NULL;
ListNode *head1=NULL;
ListNode *head2=NULL;
while(p!=NULL)
{
ListNode *tmp;
if(p->val<x)
{
tmp=new ListNode(p->val);
if(p0==NULL) head1=tmp;
else p0->next=tmp;
p0=tmp;
} p=p->next;
} ListNode *head1End=p0;
p=head;
p0=NULL;
while(p!=NULL)
{
ListNode *tmp;
if(p->val>=x)
{
tmp=new ListNode(p->val);
if(p0==NULL) head2=tmp;
else p0->next=tmp;
p0=tmp;
}
p=p->next;
} if(head1End!=NULL) head1End->next=head2;
else head1=head2; return head1;
}
};
第二种思路,与第一种方法类似,只是不新建链表进行存储
 /**
* 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 *p=head; ListNode *head1=NULL;
ListNode *head2=NULL; ListNode *p0=NULL;
ListNode *p1=NULL; while(p!=NULL)
{
if(p->val<x)
{
if(p0==NULL) head1=p;
else p0->next=p;
p0=p;
}
else
{
if(p1==NULL) head2=p;
else p1->next=p;
p1=p;
} p=p->next;
} if(p1!=NULL) p1->next=NULL;
if(p0!=NULL) p0->next=head2;
else head1=head2; return head1;
}
};