16:合并两个排序的链表

2019-08-06  本文已影响0人  iwtbam

题目描述

解题思路

AC代码

class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        if (!pHead1)
            return pHead2;

        if (!pHead2)
            return pHead1;


        ListNode* temp1 = pHead1->val < pHead2->val? pHead1 : pHead2;
        ListNode* temp2 = pHead1->val < pHead2->val? pHead2 : pHead1;
        ListNode* nHead = temp1;
        ListNode* pre = temp1;

        while (temp2) {

            while (temp1&&temp2->val >= temp1->val) {
                pre = temp1;
                temp1 = temp1->next;
            }

            if (temp1) {
                pre->next = temp2;
                ListNode* temp22 = temp2->next;
                temp2->next = temp1;
                pre = temp2;
                temp2 = temp22;
            }
            else{
                pre->next = temp2;
                return nHead;
            }
                
        }

        return nHead;
    }
};
上一篇下一篇

猜你喜欢

热点阅读