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.
/**
* 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) {
}
};
解题思路:
-
自己的解题思路
其实,题目表述存在问题,不知道这个有序到底从小到大还是从大到小,但是默认都是升序。所以,就按升序来了。题目本身很简单,不做过多解释。我这种方法属于
iterative
形式的。
-
别人的解题思路
提出一个
recursive
的方法。
学习收获:
-
第二个链表类题目。还是使用的尾插法,可以熟悉一下头插法。
-
有时, LeetCode 上面的题目表述不明确。
附件:程序
1
、自己的程序:
/**
* 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
==
NULL
)
{
return
l2
;
}
if
(
l2
==
NULL
)
{
return
l1
;
}
ListNode
head
(
0
);
ListNode
*
res
=
&
head
;
ListNode
*
p
=
res
;
while
(
l1
&&
l2
)
{
if
(
l1
->
val
<
l2
->
val
)
{
p
->
next
=
l1
;
l1
=
l1
->
next
;
}
else
{
p
->
next
=
l2
;
l2
=
l2
->
next
;
}
p
=
p
->
next
;
}
p
->
next
=
l1
?
l1
:
l2
;
return
res
->
next
;
}
};
2
、别人的程序
class
Solution
{
public
:
ListNode
*
mergeTwoLists
(
ListNode
*
l1
,
ListNode
*
l2
)
{
if
(
l1
==
NULL
)
return
l2
;
if
(
l2
==
NULL
)
return
l1
;
if
(
l1
->
val
<
l2
->
val
)
{
l1
->
next
=
mergeTwoLists
(
l1
->
next
,
l2
);
return
l1
;
}
else
{
l2
->
next
=
mergeTwoLists
(
l2
->
next
,
l1
);
return
l2
;
}
}
};