C++ leetcode刷题复盘7: merge two sorted lists

解法参考:https://www.cnblogs.com/grandyang/p/4086297.html
相关知识:
1.单链表

解法一

使用链表,以及双指针,讲两个链表内的东西放入第三个链表。

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *dummy = new ListNode(-1), *cur = dummy;//双指针,指向指针位置
        while (l1&&l2){//两个链表皆不为空
            if(l1->val < l2->val){//链表内容大小比较
                cur->next = l1;//链表填入内容
                l1= l1->next;//链表指向下一位
            }
            else
            {
                cur->next = l2;
                l2=l2->next;
            }
            cur = cur->next;
        }
        cur->next = l1?l1:l2;
        return dummy->next;
    }
};

运行速度:
在这里插入图片描述

解法二

使用递归思想。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if (!l1) return l2;
        if (!l2) return l1;
        if (l1->val < l2->val){
            l1->next = mergeTwoLists(l1->next,l2);
            return l1;
        }
        else
        {
            l2->next = mergeTwoLists(l1,l2->next);
            return l2;
        }
    }
};

运行速度:
在这里插入图片描述

解法三

简化版,没怎么看明白。

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(!l1 ||(l2 && l1->val > l2->val)) swap(l1,l2);
        if(l1) l1->next = mergeTwoLists(l1->next,l2);
        return l1;
    }
};

运行速度:
在这里插入图片描述

复盘

1.链表对于next是指向下一位置还是别的意义,需要重新学习。
2.递归思想没有很看明白(说到底不明白为什么没有循环也可以

猜你喜欢

转载自blog.csdn.net/Amberfd/article/details/112475185