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

88. Merge Sorted Array类似,数据结构不一样,这里是合并链表。

由于是链表,不能像数组一样有从后面往前写的技巧。

解法1:dummy list,新建一个链表,然后两个链表中从头各取一个元素进行比较,小的写入新链表,直到结束,返回dummy.next。

解法2:recursion,代码简洁,但空间复杂度高O(n)

Java:

public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode flag = new ListNode(0);
ListNode firstflag = flag;
while (l1 != null && l2 != null) {
if(l1.val < l2.val){
flag.next = l1;
l1 = l1.next;
}else {
flag.next = l2;
l2 = l2.next;
}
flag = flag.next;
}
flag.next = l1 != null ? l1 : l2;
return firstflag.next;
}
}

Java:

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;
}
} 

Python: Time: O(n), Space: O(1)

class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None def __repr__(self):
if self:
return "{} -> {}".format(self.val, self.next) class Solution(object):
def mergeTwoLists(self, l1, l2):
curr = dummy = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
curr.next = l1
l1 = l1.next
else:
curr.next = l2
l2 = l2.next
curr = curr.next
curr.next = l1 or l2
return dummy.next

Python: wo

class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
head = ListNode(0)
dummy = head
while l1 or l2:
if l1 and l2:
if l1.val < l2.val:
dummy.next = l1
dummy = dummy.next # required
l1 = l1.next
else:
dummy.next = l2
dummy = dummy.next # required
l2 = l2.next
elif l1:
dummy.next = l1
break
elif l2:
dummy.next = l2
break return head.next

Python: Recursion

class Solution(object):
def mergeLists(head1, head2):
temp = None
if head1 is None:
return head2 if head2 is None:
return head1 if head1.val <= head2.val:
temp = head1
temp.next = mergeLists(head1.next, head2) else:
temp = head2
temp.next = mergeLists(head1, head2.next) return temp  

Python: Recursive, wo, Time: O(n), Space: O(n)

class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
return l2 if not l2:
return l1 if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2  

Python:  in-place, iteratively

def mergeTwoLists(self, l1, l2):
if None in (l1, l2):
return l1 or l2
dummy = cur = ListNode(0)
dummy.next = l1
while l1 and l2:
if l1.val < l2.val:
l1 = l1.next
else:
nxt = cur.next
cur.next = l2
tmp = l2.next
l2.next = nxt
l2 = tmp
cur = cur.next
cur.next = l1 or l2
return dummy.next

C++: Time: O(n), Space: O(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) {
ListNode dummy{0};
auto curr = &dummy; while (l1 && l2) {
if (l1->val <= l2->val) {
curr->next = l1;
l1 = l1->next;
} else {
curr->next = l2;
l2 = l2->next;
}
curr = curr->next;
}
curr->next = l1 ? l1 : l2; return dummy.next;
}
};

C++: Recursive

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;
}
}
};

类似题目:

[LeetCode] 23. Merge k Sorted Lists 合并k个有序链表

[LeetCode] 88. Merge Sorted Array 合并有序数组

All LeetCode Questions List 题目汇总

[LeetCode] 21. Merge Two Sorted Lists 合并有序链表的更多相关文章

  1. LeetCode 21. Merge Two Sorted Lists合并两个有序链表 (C++)

    题目: Merge two sorted linked lists and return it as a new list. The new list should be made by splici ...

  2. [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 t ...

  3. leetcode 21 Merge Two Sorted Lists 合并两个有序链表

    描述: 合并两个有序链表. 解决: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (!l1) return l2; if (!l2) ...

  4. [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 t ...

  5. LeetCode 21 Merge Two Sorted Lists (有序两个链表整合)

    题目链接 https://leetcode.com/problems/merge-two-sorted-lists/?tab=Description   Problem: 已知两个有序链表(链表中的数 ...

  6. leetcode 题解Merge Two Sorted Lists(有序链表归并)

    题目: Merge two sorted linked lists and return it as a new list. The new list should be made by splici ...

  7. 21. Merge Two Sorted Lists(合并2个有序链表)

    21. Merge Two Sorted Lists Merge two sorted linked lists and return it as a new list. The new list s ...

  8. 【LeetCode】21. Merge Two Sorted Lists 合并两个有序链表

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:合并,有序链表,递归,迭代,题解,leetcode, 力 ...

  9. [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 t ...

随机推荐

  1. SHA-1算法——(2)

    地址:https://www.alvestrand.no/objectid/1.3.14.3.2.26.html 地址:http://oidref.com/1.3.14.3.2.26 这个值好像是个标 ...

  2. Codeforces Round #598 (Div. 3)- E. Yet Another Division Into Teams - 动态规划

    Codeforces Round #598 (Div. 3)- E. Yet Another Division Into Teams - 动态规划 [Problem Description] 给你\( ...

  3. 动态规划——背包问题python实现(01背包、完全背包、多重背包)

    目录 01背包问题 完全背包问题 多重背包问题 参考: 背包九讲--哔哩哔哩 背包九讲 01背包问题 01背包问题 描述: 有N件物品和一个容量为V的背包. 第i件物品的体积是vi,价值是wi. 求解 ...

  4. Rendering in UE4

    Intro Thinking performance. Identify the target framerate, aim your approach on hitting that target ...

  5. 通俗理解word2vec的训练过程

    https://www.leiphone.com/news/201706/eV8j3Nu8SMqGBnQB.html https://blog.csdn.net/dn_mug/article/deta ...

  6. 《CoderXiaoban》第八次团队作业:Alpha冲刺

    项目 内容 这个作业属于哪个课程 任课教师博客主页链接 这个作业的要求在哪里 实验十二 团队作业8:软件测试与ALPHA冲刺 团队名称 Coderxiaoban团队 作业学习目标 (1)掌握软件测试基 ...

  7. noip初赛试题

    链接: https://pan.baidu.com/s/1yoOMIUqMRBnBUPprC3o6HQ&shfl=shareset 提取码: m8ns 复制这段内容后打开百度网盘手机App,操 ...

  8. c++ sprintf() 用法

    1. char  boxData[100]; fi.mWidth = 1.0, fi.mCenter_x= 2.1, fi.mCenter_y=1.1; sprintf(boxData, " ...

  9. CLR内部异常(上)

    当我们提到CLR里的“异常”,要注意一个很重要的区别.有通过如C#的try/catch/finally暴露给应用程序,并由运行时提供机制全权实现的托管异常.也有运行时自己使用的异常.大部分运行时开发人 ...

  10. VSCode 本地如何查看历史页面

    1.首先要在VSCode的扩展中安装一个 Local history插件,蓝色框部分不用管,直接安装即可 2.安装并操作:安装后,修改 productManage/supplierList/addSu ...