Files
leetcode-master/problems/0021.合并两个有序链表.md
youngyangyang04 18516eb768 Update
2020-06-29 08:59:41 +08:00

1.7 KiB
Raw Blame History

题目地址

https://leetcode-cn.com/problems/merge-two-sorted-lists/

思路

链表的基本操作,一下代码中有详细注释

代码

/**
 * 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:
// 题目中我们为什么定义了一个 新的head
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* head = new ListNode();
        ListNode* index = head;
        while(l1 != nullptr && l2 != nullptr) { // 注意null 和nullptr的区别
            if (l1->val < l2->val) {
                index->next = l1;
                l1 = l1->next;
            } else {
                index->next = l2;
                l2 = l2->next;
            }
            index = index->next;
        }
        if (l1 != nullptr) {
            index->next = l1;
            l1 = l1->next;
        }
        if (l2 != nullptr) {
            index->next = l2;
            l2 = l2->next;
        }
        ListNode* tmp = head; // 注意清理内存,不清理也没事
        head = head->next;
        delete tmp;
        return head;
        // return head->next

    }
};

更多精彩文章持续更新,可以微信搜索「 代码随想录」第一时间阅读,关注后有大量的学习资料和简历模板可以免费领取,本文 GitHubhttps://github.com/youngyangyang04/leetcode-master 已经收录欢迎starfork共同学习一起进步。