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

来源:互联网 发布:php html转markdown 编辑:程序博客网 时间:2024/06/08 07:40
  • 合并两个有序链表,合并以后的链表依旧有序。
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
原创粉丝点击