合併鏈表和求1+2+...+n不用循環、乘除法、循環、條件判斷、選擇相關的關鍵字

合併鏈表

這裏就不說了,稍微看下代碼應該就可以懂了
遞歸:

ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        // write your code here
       if(l1==NULL||l2==NULL)
            return l1==NULL?l2:l1;
        ListNode* head=NULL;
        if(l1->val > l2->val)
            head=l2;            
        else
            head=l1;
        if(l1->val>l2->val)
            head->next=mergeTwoLists(l1,l2->next);
        else
            head->next=mergeTwoLists(l1->next,l2);
};

非遞歸:

ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        // write your code here
        if(l1==NULL || l2 == NULL)
            return l1==NULL?l2:l1;

        ListNode* head=NULL,*cur=NULL,*tmp1=l1,*tmp2=l2;
        if(l1->val > l2->val)
        {
                head=l2;
                tmp2=head->next;
        }
        else
        {
            head=l1;
            tmp1=head->next;
        }   
        cur=head;
        while(tmp1&&tmp2)
        {   
            if(tmp1->val > tmp2->val)
                { 
                       cur->next=tmp2;
                       tmp2=tmp2->next;
                }
            else
                {
                    cur->next=tmp1;
                    tmp1=tmp1->next;
                }      
            cur=cur->next;
        }
        if(tmp1==NULL)
            cur->next=tmp2;
        else
            cur->next=tmp1;

        return head;
    }
};

求1+2+…+n不用循環、乘除法、循環、條件判斷、選擇相關的關鍵字

這有很多方法,這只是其中一種

namespace t1{
    class test
    {
    public:
        test()
        {
            a++;
        }
        int get_a()
        {
            return a;
        }
    protected:
        static int a;
    };
    int test::a = 0;
    int main()
    {
        test* t1 = new test[100];
        printf("%d", t1->get_a());
        return 0;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章