86. Partition List

来源:互联网 发布:热设计软件 编辑:程序博客网 时间:2024/05/01 09:55

方法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;    }};


0 0