21 Merge Two Sorted Lists
链接:https://leetcode.com/problems/merge-two-sorted-lists/
问题描述:
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.
Hide Tags Linked List
这个问题就是合并从小到大的两个排序好的链表。
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *t=new ListNode(0),*p=t;
while(l1&&l2)
{
if(l1->val<l2->val)
{
t->next=l1;
t=l1;
l1=l1->next;
}
else
{
t->next=l2;
t=l2;
l2=l2->next;
}
}
if(l1)
t->next=l1;
if(l2)
t->next=l2;
t=p->next;
delete p;
return t;
}
};