LeetCode刷题(187)~合并两个排序的链表【伪节点|递归】

    科技2026-02-16  14

    题目描述

    输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

    示例1:

    输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4

    限制:

    0 <= 链表长度 <= 1000

    解答 By 海轰

    提交代码(伪节点)

    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* res=new ListNode(INT_MIN); ListNode* cur=res; while(l1 && l2){ if(l1->val<l2->val){ cur->next=l1; l1=l1->next; cur=cur->next; }else{ cur->next=l2; l2=l2->next; cur=cur->next; } } cur->next= l1? l1:l2; return res->next; }

    运行结果 提交代码(递归)

    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; } }

    运行结果

    题目来源

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof

    海轰Pro 认证博客专家 C/C++ 微信小程序 微信小程序:「海轰Pro」微信公众号:「海轰Pro」知乎:「海轰Pro」微博:「海轰Pro」
    Processed: 0.015, SQL: 9