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.
注意:
最后返回值的时候,不能返回newlist,因为newlist的指针已经指到后面去了,而在这个ListNode中没有head,因此需要一个新的result来存储newlist的开始点。
/**
* 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 *newlist=new ListNode(0);
ListNode *result=newlist;
if(l1==NULL) return l2;
if(l2==NULL) return l1;
if(l1==NULL && l2==NULL) return NULL;
while(l1&&l2)
{
if(l1->val > l2->val)
{
newlist->next=l2;
l2=l2->next;
}
else
{
newlist->next=l1;
l1=l1->next;
}
newlist=newlist->next;
}
if(l1) newlist->next=l1;//比较完之后,数组剩下来的数
if(l2) newlist->next=l2;
return result->next;
}
};