链表的分化练习

对于一个链表,我们需要用一个特定阈值完成对它的分化,使得小于等于这个值的结点移到前面,大于该值的结点在后面,同时保证两类结点内部的位置关系不变。
给定一个链表的头结点head,同时给定阈值val,请返回一个链表,使小于它的结点在前,大于它的在后,d等于它的节点在中间。保证结点值不重复。
测试样例:
{1,4,2,5},3
{1,2,4,5}

两种做法,第一种可以直接将链表放到一个数组中,然后类似荷兰国旗问题进行处理。空间复杂度为O(n)
第二种直接操作链表,给定三个链表头:分别指向小于,相等,大于。之后拼接三个链表即可
代码如下:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};*/
class Divide {
public:
    ListNode* listDivide(ListNode* head, int val) {
        if(!head)
            return NULL;
        ListNode* less=new ListNode(0);
        ListNode* equ=new ListNode(0);
        ListNode* more=new ListNode(0);

        ListNode* templess=less;
        ListNode* tempequ=equ;
        ListNode* tempmore=more;
        while(head)
            {
            if(head->val<val){                
                templess->next=head;
                templess=templess->next;
                head=head->next;
            }
            else if(head->val==val)
                {
                tempequ->next=head;
                tempequ=tempequ->next;
                head=head->next;                
            }
            else
                {
               tempmore->next=head;
               tempmore=tempmore->next;
               head=head->next; 
            }                
        }
        if(less->next&&equ->next&&more->next)
            {
            templess->next=equ->next;
            tempequ->next=more->next;
            tempmore->next=NULL;
            return less->next;
        }
        else if(less->next&&!equ->next&&more->next)
            {
            templess->next=more->next;
            tempmore->next=NULL;
            return less->next;
        }
        else if(less->next&&equ->next&&!more->next)
            {
            templess->next=equ->next;
            tempequ->next=NULL;
            return less->next;
        }
        else if(!less->next&&equ->next&&more->next)
            { 
            tempequ->next=more->next;
            tempmore->next=NULL;
            return equ->next;            
        }
        else if(!less->next&&!equ->next&&more->next)
            {
            tempmore->next=NULL;
            return more->next;            
        }
        else 
            {
            tempequ->next=NULL;
            return equ->next;            
        }
       return NULL;

    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值