每日一题2023.7.18|21.合并两个有序链表

21.合并两个有序链表

链接:LeetCode21.合并两个有序链表
为了方便解题,需要设置一个虚拟头结点

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        //虚拟头结点
        ListNode *listnode = new ListNode();
        ListNode *node = listnode;
        ListNode *l1=list1,*l2=list2;
        while(l1&&l2){
            if(l1->val<=l2->val) {node->next=l1;l1=l1->next;}
            else {node->next=l2;l2=l2->next;}
            node = node->next;
        }
        if(l1) node->next = l1;
        if(l2) node->next= l2;
        return listnode->next;
    }
};

你可能感兴趣的:(数据结构与算法之美,链表,数据结构,c++,leetcode)