class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
ListNode* phead = nullptr,*temp = nullptr;
phead = new ListNode;
phead->val = 0,phead->next = nullptr;
temp = phead;
while(list1 != nullptr && list2 != nullptr){
if(list1->val < list2->val){
temp->next = list1;
list1 = list1->next;
}
else{
temp->next = list2;
list2 = list2->next;
}
temp = temp->next;
}
temp->next = list1 ? list1 : list2;
ListNode* ptemp = phead;
phead = phead->next;
delete ptemp;
ptemp = nullptr;
return phead;
}
};
合并两个有序链表
最新推荐文章于 2024-11-12 20:24:31 发布