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.
Sort List里面也有实现。
/**
* 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(0);
ListNode *plist;
plist = &newlist;
while(l1 != NULL && l2 != NULL)
{
if(l1->val <= l2->val)
{
plist->next = l1;
plist = plist->next;
l1 = l1->next ;
}
else
{
plist->next = l2;
plist = plist->next;
l2 = l2->next ;
}
}
if(l1 != NULL )
{
plist->next = l1;
}
else if(l2 != NULL)
{
plist->next = l2;
}
return newlist.next;
}
};