题目:

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* pre=new ListNode(0);             //创建pre指针,也相当于是新链表的虚拟头结点
        ListNode* head=pre;                        //记录最终要返回链表的虚拟头结点
        while(l1&&l2){
            auto& small=l1->val<l2->val?l1:l2;     //这个&是精髓,将两个链表中小的节点赋予small这个引用
            pre->next=small;                       //新链表加入小的节点
            small=small->next;                     //因为是引用,相当于更新了l1或l2中小节点的指针
            pre=pre->next;                         //更新pre指针,准备加入下一个节点
        }
        pre->next=l1?l1:l2;                        //新链表接上剩余的链表
        return head->next;                         //返回新链表
    }
};

以上代码方法转自力扣评论区

posted on 2023-07-25 20:48  孜孜不倦fly  阅读(10)  评论(0)    收藏  举报