数据结构——以给定值x为基准将链表分割成两部分

作者:小 琛
欢迎转载,请标明出处

题目:
在这里插入图片描述
思路分析:
要将链表以x为基准分割,可以就是否大于x为判断法则,开辟两个新的链表head1和head2,在保证顺序不变的情况下,最后将两个链表合并。
技巧1:可以先遍历链表一遍,找到该链表是否含有x,得到其数量
技巧2:创立得链表可以是带头得,方便操作,返回得时候将头去掉即可
在这里插入图片描述

class Partition {
public:
    ListNode* buynewnode(int x)
    {
        ListNode* newnode=(ListNode*)malloc(sizeof(ListNode));
        newnode->val=x;
        newnode->next=NULL;
        return newnode;
    }
    void pushback(ListNode** pphead,int x)
    {
        ListNode* newnode=buynewnode(x);
        if ((*pphead)==NULL)
        {
            (*pphead)=newnode;
        }
        else{
            ListNode* tail=(*pphead);
            while (tail->next!=NULL)
                tail=tail->next;
            tail->next=newnode;
        }
    }
    ListNode* partition(ListNode* pHead, int x) {
        if (pHead==NULL||pHead->next==NULL)
            return pHead;
        ListNode* cur=pHead;
        ListNode* head1=(ListNode*)malloc((sizeof(ListNode)));
        ListNode* head2=(ListNode*)malloc((sizeof(ListNode)));
        ListNode* tail1=NULL;
        ListNode* tail2=NULL;
        int count=0;
        while (cur!=NULL)
        {
            if (cur->val==x)
                count++;
            cur=cur->next;
        }
        if (count==0)
        {
            head1->next=NULL;
            head2->next=NULL;
        }
        else{
            tail1=head1;
            tail2=head2;
            head1->next=NULL;
            while (count)
            {
                tail2->next=buynewnode(x);
                tail2=tail2->next;
            }
        }
        cur=pHead;
        while (cur!=NULL)
        {
            if (cur->val<x)
            {
                pushback(&tail1,cur->val);
                cur=cur->next;
                tail1=tail1->next;
            }
            else if(cur->val>x)
            {
                pushback(&tail2,cur->val);
                cur=cur->next;
                tail2=tail2->next;
            }
            else
                cur=cur->next;
        }
        if (head1->next==NULL)
            return head2->next;
        else if (head2->next==NULL)
            return head1->next;
        else{
            tail1->next=head2->next;
            return head1->next;
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值