day01之合并两个有序链表+实现1+2+3...+n要求不能使用乘除法循环条件判断等

  • 合并两个有序链表,合并以后的链表依旧有序。
struct Node
{
    Node * next;
    int value;

    Node(int val):value(val),next(NULL)
    {

    }
};

//方式一:非递归写法。
Node * UnitSeqList(Node *phead1, Node *phead2)
{
    if(phead1 == NULL)
        return phead2;
    if(phead2 == NULL)
        return phead1;

    Node *phead = NULL;
    Node *p1 = phead1;
    Node *p2 = phead2;
    Node *pm = phead;

    if(p1->value < p2->value)
    {
        phead = pm = p1;
        p1 = p1->next;
    }
    else
    {
        phead = pm = p2;
        p2 = p2->next;
    }

    while(p1 != NULL && p2 != NULL)
    {
        if(p1->value < p2->value)
        {
            pm->next = p1;
            pm = p1;
            p1 = p1->next;
        }
        else
        {
            pm->next = p2;
            pm = p2;
            p2 = p2->next;
        }
    }
    if(p1 != NULL)
        pm->next = p1;
    else
        pm->next = p2;

    return phead;
}


Node* UnitSeqList2(Node *phead1, Node *phead2)
{
    if(phead1 == NULL)
        return phead2;
    if(phead2 == NULL)
        return phead1;
    Node *phead = NULL;
    if(phead1->value < phead2->value)
    {
        phead= phead1;
        phead->next = UnitSeqList2(phead1->next, phead2);
    }
    else
    {
        phead = phead2;
        phead->next = UnitSeqList2(phead1, phead2->next);
    }

    return phead;
}
  • 实现1+2+3…+n,要求不能使用乘除法、循环、条件判断、选择相关的关键字。(这个题有多种解法,大家可以尽量去思考,这个题最优的解法时间复杂度是O(1)
//方式一: 利用逻辑或的短路规则加上递归。
int fun(int n)
{
    int ret = 0;
    (n==0)||(ret=fun(n-1));
    return ret+n;
}

//方式二:利用静态变量加构造函数。
struct test
{
    test()
    {
        num++;
        result += num;
    }

    static int  addresult()
    {
        return result;
    }

    static int num ;
    static int result;
};

int test::num = 0;
int test::result = 0;

//方式三:利用虚函数。

class A;
A*array[2];
class A   //基类处理n==0这种情况
{
    public:
        virtual int sum(int n)
        {
            return 0;
        }
};

class B:public A  //子类累加求和
{
    public:
        virtual int sum(int n)
        {
            return n+array[!!n]->sum(n-1); //非0数!!变成1,指向子类,0!!依能变成0指向基类。
        }
};

int Num(int n)
{
    A a;
    B b;
    array[0] = &a;
    array[1] = &b;

    return array[1]->sum(n);  

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值