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. 洛谷 P2921 在农场万圣节Trick or Treat on the Farm题解

    题意翻译 题目描述 每年,在威斯康星州,奶牛们都会穿上衣服,收集农夫约翰在N(1<=N<=100,000)个牛棚隔间中留下的糖果,以此来庆祝美国秋天的万圣节. 由于牛棚不太大,FJ通过指定 ...

  2. Codeforces E. Weakness and Poorness(三分最大子列和)

    题目描述: E. Weakness and Poorness time limit per test 2 seconds memory limit per test 256 megabytes inp ...

  3. postgres linux系统下连接方法

    psql -U 用户名 -h ip  -p 端口号 -w 库名称 查询实例下的数据结构 语法:select 字段名  from  实例名“.”表名(account.tb_user) 如:  selec ...

  4. JS 不声明第三个变量的情况下实现两数变换

    1. var a = 1; var b = 2; a = a + b; b = a - b; a = a - b; console.log(a); console.log(b); 2. var a = ...

  5. CentOS7中使用yum安装nginx和php7.2的方法

    c 1.安装源 安装php72w,是需要配置额外的yum源地址的,否则会报错不能找到相关软件包. php高版本的yum源地址,有两部分,其中一部分是epel-release,另外一部分来自webtat ...

  6. php Web 项目的文件/文件夹上传下载

    PHP用超级全局变量数组$_FILES来记录文件上传相关信息的. 1.file_uploads=on/off 是否允许通过http方式上传文件 2.max_execution_time=30 允许脚本 ...

  7. 洛谷 P1629 邮递员送信 题解

    P1629 邮递员送信 题目描述 有一个邮递员要送东西,邮局在节点1.他总共要送N-1样东西,其目的地分别是2~N.由于这个城市的交通比较繁忙,因此所有的道路都是单行的,共有M条道路,通过每条道路需要 ...

  8. 计蒜客 39279.Swap-打表找规律 (The 2019 ACM-ICPC China Shannxi Provincial Programming Contest L.) 2019ICPC西安邀请赛现场赛重现赛

    Swap There is a sequence of numbers of length nn, and each number in the sequence is different. Ther ...

  9. 原创:协同过滤之spark FP-Growth树应用示例

    上一篇博客中,详细介绍了UserCF和ItemCF,ItemCF,就是通过用户的历史兴趣,把两个物品关联起来,这两个物品,可以有很高的相似度,也可以没有联系,比如经典的沃尔玛的啤酒尿布案例.通过Ite ...

  10. CodeMirror在线代码编辑器使用

    CodeMirror官网地址为:https://codemirror.net/ CodeMirror作为一款代码编辑器,其应用场景主要是在线网站写代码.如现在的leetcode.洛谷.code-vs等 ...