leetcode21 C++ 8ms 合并两个有序链表

Posted 一条图图犬

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode21 C++ 8ms 合并两个有序链表相关的知识,希望对你有一定的参考价值。

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

        head->next = l1 != nullptr ? l1: l2;
        return res;
    }
};

以上是关于leetcode21 C++ 8ms 合并两个有序链表的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode No.21 Merge Two Sorted Lists合并两个有序链表(c++实现)

精选力扣500题 第7题 LeetCode 21. 合并两个有序链表c++详细题解

精选力扣500题 第22题 LeetCode 88. 合并两个有序数组c++详细题解

[leetcode] 21. 合并两个有序链表

leetcode-21-合并两个有序链表

LeetCode Algorithm 21. 合并两个有序链表