• 剑指offer--面试题17


    题目:合并两个排序的单向链表

    自己所写代码如下:

    ListNode* MergeSortedLists(ListNode* pHead1, ListNode* pHead2)
    {
        if(pHead1 == NULL || pHead2 == NULL)
            return NULL;
        return (pHead1->value < pHead2->value)? MergeTwoList(pHead1,pHead2):MergeTwoList(pHead2,pHead1);
    }
    
    ListNode* MergeTwoList(ListNode* pFirst,ListNode* pSecond)
    {
        ListNode* pHead = pFirst;
        ListNode* ptemp = pSecond;
    
        while(pHead->pNext != NULL || ptemp->pNext != NULL)
        {
            while(pHead->pNext != NULL && pHead->pNext->value <= ptemp->value)
                pHead = pHead->pNext;
    
            ListNode* pHead1 = pHead->pNext;
            ListNode* ptemp1 = ptemp->pNext;
            ptemp->pNext = pHead->pNext;
            pHead->pNext = ptemp;
            ptemp = ptemp1;
            pHead = pHead1;
        }
    
        if(pHead->pNext == NULL)
            pHead->pNext = ptemp;
    
        return pFirst;
    }

    PS:未经测试!

    作者分析的太精辟了!相比之下,自己的思路还不够完善,同时没有想到用递归实现。。。

    //思路:两个链表中的头结点作比较,较小的被选为‘头结点’并链接到前一节点之后;
    //      不断缩小规模,直到某个链表为空!
    //所以递归!
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        //递归终止条件
        //经典!
        if(pHead1 == NULL)
            return pHead2;
        else if(pHead2 == NULL)
            return pHead1;
    
        ListNode* pMerged = NULL;
        if(pHead1->value < pHead2->value)
        {
            pMerged = pHead1;
            pMerged->pNext = Merge(pHead1->pNext,pHead2);
        }
        else
        {
            pMerged = pHead2;
            pMerged->pNext = Merge(pHead1,pHead2->pNext);
        }
    
        return pMerged;
            
    }
    清醒时做事,糊涂时读书,大怒时睡觉,独处时思考; 做一个幸福的人,读书,旅行,努力工作,关心身体和心情,成为最好的自己 -- 共勉
  • 相关阅读:
    hbase与Hive的集成
    HBase API操作
    HBase原理
    HBase数据结构
    HBase Shell操作
    HBase简介
    Boxes in a Line
    B
    B. Painting Pebbles
    X
  • 原文地址:https://www.cnblogs.com/hello-yz/p/3255238.html
Copyright © 2020-2023  润新知