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

LeetCode-21.合并两个有序链表,第1张

21.合并两个有序链表

  • 题目描述

将两个升序链表合并为一个新的 升序 链表并返回。

新链表是通过拼接给定的两个链表的所有节点组成的。


21.合并两个有序链表

  • 代码

比较经典的链表问题(直接上代码哈哈)

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        ListNode head;
        ListNode *p , *q;
        p = &head;
        q = &head;
        if(!list1 && !list2){
            return nullptr;
        }
        while(list1 && list2){
            if(list1 -> val <= list2 ->val){
                p -> next = list1;
                p = list1;
                list1 = list1 -> next;
            }
            else{
                p -> next = list2;
                p = list2;
                list2 = list2 -> next;
            }    
        }
        p -> next = list1 ? list1 : list2;
        return q -> next;
    }
};

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/673306.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-19
下一篇 2022-04-19

发表评论

登录后才能评论

评论列表(0条)

保存