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.
两个有序链表归并成一个有序链表,
其实比较优美的解法是用递归去解决,代码十分简洁,
然而我之前有题目这样做过了,就想用大众化的方法做一遍。
http://blog.csdn.net/accepthjp/article/details/52356447
/**
* 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* p=new ListNode(0);
ListNode* result=p;
while(l1 && l2)
{
ListNode* t=new ListNode(0);
p->next=t;
p=p->next;
if(l1->val<l2->val)
{
p->val=l1->val;
l1=l1->next;
}
else
{
p->val=l2->val;
l2=l2->next;
}
}
p->next=l1?l1:l2;
return result->next;
}
};