/**
* 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 *root = new ListNode(-2,nullptr) ;
ListNode *head = root ;
while (list1 && list2 )
{
if (list1->val > list2->val )
{
ListNode *node = new ListNode(list2->val,nullptr) ;
head->next = node ;
head = head->next ;
list2 = list2->next ;
}
else
{
ListNode *node = new ListNode(list1->val,nullptr) ;
head->next = node ;
head = head->next ;
list1 = list1->next ;
}
}
if (list1)
{
head->next = list1 ;
}
if (list2)
{
head->next = list2 ;
}
return root->next ;
}
};
leecode 合并连表
最新推荐文章于 2024-09-03 17:14:20 发布