21. Merge Two Sorted Lists(合并有序链表)
2018-03-11 22:36
316 查看
Description: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->4Solution:
可以用递归的方法实现合并有序链表。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(l1, l2->next);
return l2;
}
}
};
Output: 1->1->2->3->4->4Solution:
可以用递归的方法实现合并有序链表。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(l1, l2->next);
return l2;
}
}
};
相关文章推荐
- Leetcode刷题记——21. Merge Two Sorted Lists(合并两有序链表)
- 21. Merge Two Sorted Lists(合并有序链表)
- [LeetCode] 21. Merge Two Sorted Lists 合并两个有序链表 @python
- 21. Merge Two Sorted Lists(合并2个有序链表)
- 21. Merge Two Sorted Lists (Java 合并有序链表 空间复杂度O(1))
- [LeetCode] Merge Two Sorted Lists 合并两个有序链表
- Merge Two Sorted Lists 合并两个有序链表@LeetCode
- leetcode Merge Two Sorted Lists 合并两个有序链表
- Merge Two Sorted Lists(合并两个有序链表)
- LeetCode(Merge Two Sorted Lists ) 合并两个有序的链表
- [LeetCode] 21. Merge Two Sorted Lists 合并有序链表
- [LeetCode]Merge Two Sorted Lists & Remove Duplicates from Sorted List 两个有序链表合并为一个&删除链表重复元素
- [LeetCode 21]Merge Two Sorted Lists 合并两个有序链表
- 21. Merge Two Sorted Lists (合并两个链表) Review
- LeetCode OJ 之 Merge Two Sorted Lists(合并两个有序的链表)
- Merge Two Sorted Lists, 合并两个有序链表
- LeetCode Merge Two Sorted Lists(合并两个有序链表)
- 面试题17:合并两个有序链表(Leetcode-21:Merge Two Sorted Lists)
- LeetCode 21. Merge Two Sorted Lists (合并两个有序链表)
- LeetCode--Merge Two Sorted Lists(合并两个有序链表)Python