/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *ans=new ListNode(0);
ListNode *answer=ans;
while(l1 && l2){
if(l1->val<l2->val){
ans->next=l1;
ans=ans->next;
l1=l1->next;
}
else{
ans->next=l2;
l2=l2->next;
ans=ans->next;
}
}
if(l1){
ans->next=l1;
}
if(l2){
ans->next=l2;
}
return answer->next;
}
};
Leetcode: Merge Two Sorted Lists
最新推荐文章于 2024-05-07 23:40:32 发布