方法1:插入&删除
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode* Head=new ListNode(-1);
Head->next=head;
ListNode* pre=Head,*cur=head,*p=pre;
while(cur)
{
if(cur->val<x)
{
if(pre->next==cur)
{
p=pre=cur;
cur=cur->next;
}
else
{
ListNode* nx=cur->next;
cur->next=pre->next;
pre=pre->next=cur;
p->next=nx;
cur=nx;
}
}
else
{
p=cur;
cur=cur->next;
}
}
return Head->next;
}
};方法2:
建立两个链表
class Solution {
public:
ListNode* partition(ListNode* head, int x) {
ListNode* left=new ListNode(-1);
ListNode* right=new ListNode(-1);
ListNode* l=left,*r=right;
ListNode* p=head;
while(p)
{
if(p->val<x)
l=l->next=p;
else
r=r->next=p;
p=p->next;
}
r->next=NULL;
l->next=right->next;
return left->next;
}
};
本文介绍了一种将链表中小于特定值x的节点移动到前面的算法,并提供了两种实现方式:一种通过直接插入和删除操作来实现,另一种通过创建两个临时链表再合并的方式来完成。
1741

被折叠的 条评论
为什么被折叠?



