leetcode_merge_two_sorted_lists

难度:Easy

注意:new一个ListNode,返回的是ListNode的指针;直接调用ListNode构造函数,返回的是ListNode。
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* 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* dummy = new ListNode(-1);
ListNode* cur = dummy;
while(l1 != NULL && l2 != NULL)
{
if(l1->val < l2->val)
{
cur->next = l1;
cur = cur->next;
l1 = l1->next;
}
else
{
cur->next = l2;
cur = cur->next;
l2 = l2->next;
}
}
if(l1 != NULL)
{
cur->next = l1;
}
if(l2 != NULL)
{
cur->next = l2;
}
return dummy->next;
}
};

运行结果:9ms,超过23.48%