面试题25:合并两个排序的链表

题目描述:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
测试用例:特殊输入
1.两个链表头节点都为空,返回空
2.有一个链表节点为空,返回另一个链表的头节点
解题思路:
1.合并两个链表从两个链表的头节点开始,比较两个头节点,找到较小的那个作为新链表的头节点。
2.将去掉头节点链表的指针向后移一位,剩下两个链表依然是递增排序的。继续比较两个头节点,找到较小的那个作为新链表的头节点。

ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if(pHead1==NULL)
            return pHead2;
        if(pHead2==NULL)
            return pHead1;
        if(pHead1==NULL&&pHead2==NULL)
            return NULL;

        ListNode *pNewHead=NULL;
        if(pHead1->val<pHead2->val){
            pNewHead=pHead1;
            pNewHead->next=Merge(pHead1->next,pHead2);
        }
        else{
            pNewHead=pHead2;
            pNewHead->next=Merge(pHead1,pHead2->next);
        }
        return pNewHead;
    }

猜你喜欢

转载自blog.csdn.net/htt789/article/details/81012172