题目:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first
two lists.
思路:
1.同时遍历,一一比较即可
代码:
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1,ListNode *l2)
{
ListNode *head=new ListNode(-1);
ListNode *tail=head,*p1=l1,*p2=l2;
while(p1 && p2)
{
if(p1->val<=p2->val)
{
tail->next=p1;
p1=p1->next;
}
else
{
tail->next=p2;
p2=p2->next;
}
tail=tail->next;
}
tail->next=!p1?p2:p1;
return head->next;
}
};