剑指offer67题-No16.合并两个有序链表

要求:空间复杂度 O(1) ,时间复杂度 O(n) 。

方法1:新链表合并,抄自牛客题解。比较直观。

class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
        auto vhead=new ListNode(-1); //设置一个哨兵指针
        ListNode *newhead=vhead;
        while(pHead1&&pHead2)
        {
            if(pHead1->val <= pHead2->val){
                newhead->next = pHead1;
                pHead1 = pHead1->next;
            }else{
                newhead->next = pHead2;
                pHead2 = pHead2->next;
            }
            newhead = newhead->next;
        }
        if(pHead2==nullptr) 
            newhead->next=pHead1;
        if(pHead1==nullptr)
            newhead->next=pHead2;
        return vhead->next;
    }
};

方法2:递归。时间复杂度:O(m+n);空间复杂度:O(m+n)。

class Solution {
public:
 ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
 {
     if (!pHead1) return pHead2;
     if (!pHead2) return pHead1;
     if (pHead1->val <= pHead2->val) {
         pHead1->next = Merge(pHead1->next, pHead2);
         return pHead1;
     }
     else {
         pHead2->next = Merge(pHead1, pHead2->next);
         return pHead2;
     }
 }
};

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇