leetcode 21. 合并两个有序链表

2023.9.24

leetcode 21. 合并两个有序链表_第1张图片

         本题思路比较简单,直接构建一个新的链表,不断加入两个给定链表的节点即可。 代码如下:

/**
 * 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* dummy = new ListNode();
        ListNode* cur1 = list1;
        ListNode* cur2 = list2;
        ListNode* cur = dummy;
        while(cur1 && cur2)
        {
            if(cur1->val < cur2->val)
            {
                cur->next = cur1;
                cur = cur->next;
                cur1 = cur1->next;
            }
            else
            {
                cur->next = cur2;
                cur = cur->next;
                cur2 = cur2->next;
            }
        }
        while(cur1)
        {
            cur->next = cur1;
            cur = cur->next;
            cur1 = cur1->next;
        }
        while(cur2)
        {
            cur->next = cur2;
            cur = cur->next;
            cur2 = cur2->next;
        }
        return dummy->next;
    }
};

你可能感兴趣的:(leetcode专栏,leetcode,链表,算法,数据结构,cpp)