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.
题意
合并两个链表,新的链表由两个链表的节点组成。
题解
和归并类似,一步步取两条链最小那个节点即可。
/**
* 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) {
if(!l1) return l2;
if(!l2) return l1;
ListNode newstart(-1);
ListNode* p=&newstart;
for(;l1!=NULL&&l2!=NULL;p=p->next)
{
if(l1->val<l2->val)
{
p->next=l1;
l1=l1->next;
}
else
{
p->next=l2;
l2=l2->next;
}
}
p->next=l1!=NULL ? l1 :l2;
return newstart.next;
}
};