AcWing 36. 合并两个排序的链表(C++)- 二路归并

题目链接:https://www.acwing.com/problem/content/description/34/
题目如下:
在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* merge(ListNode* l1, ListNode* l2) {
    
    
        ListNode* dummy=new ListNode(-1);
        ListNode* list=dummy;
        
        while(l1&&l2){
    
    
            if(l1->val>l2->val){
    
    
                list->next=l2;
                l2=l2->next;
            }else{
    
    
                list->next=l1;//因为当出现两个节点的值相等时,需全部放入链表中,所以,不能两个节点同时next
                l1=l1->next;
            }
            
            list=list->next;
        }
        
        if(l1==NULL) list->next=l2;
        else list->next=l1;
        
        return dummy->next;
    }
};

おすすめ

転載: blog.csdn.net/qq_40467670/article/details/121131218