LeetCode 21 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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
12         if(!l1&&!l2)
13             return nullptr;
14         if(!l1)
15             return l2;
16         if(!l2)
17             return l1;
18         ListNode* first=new ListNode(-1);
19         ListNode* cur=first;
20         while(l1&&l2)
21         {
22             if(l1->val<l2->val)
23             {
24                 cur->next=l1;
25                 l1=l1->next;
26             }
27             else
28             {
29                 cur->next=l2;
30                 l2=l2->next;
31             }
32             cur=cur->next;
33         }
34         cur->next=l1?l1:l2;
35         return first->next;
36     }
37 };
原文地址:https://www.cnblogs.com/xidian2014/p/8590456.html