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.
1 - 简单的链表操作
2 - 应该注意到,题目要求新的链表应该由两个旧链表接合而成。因此,我们应该仅仅修改指针,而不应该去生成一个新链表。
/**
* 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==nullptr) return l2;
if(l2==nullptr) return l1;
ListNode dummy(-1);
ListNode *p = &dummy;
for(;l1!=nullptr&&l2!=nullptr;p=p->next){
if(l1->val<l2->val){
p->next = l1;
l1 = l1->next;
}else{
p->next = l2;
l2 = l2->next;
}
}
if(l1==nullptr) p->next = l2;
else p->next = l1;
return dummy.next;
}
};