[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 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 合并有序链表的更多相关文章
- 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 ...
- [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 ...
- leetcode 21 Merge Two Sorted Lists 合并两个有序链表
描述: 合并两个有序链表. 解决: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (!l1) return l2; if (!l2) ...
- [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 ...
- LeetCode 21 Merge Two Sorted Lists (有序两个链表整合)
题目链接 https://leetcode.com/problems/merge-two-sorted-lists/?tab=Description Problem: 已知两个有序链表(链表中的数 ...
- 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 ...
- 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 ...
- 【LeetCode】21. Merge Two Sorted Lists 合并两个有序链表
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 个人公众号:负雪明烛 本文关键词:合并,有序链表,递归,迭代,题解,leetcode, 力 ...
- [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 ...
随机推荐
- beta版本——第三次冲刺
第三次冲刺 (1)SCRUM部分☁️ 成员描述: 姓名 李星晨 完成了哪个任务 认证学校那一栏增加检测机制的ui设计 花了多少时间 1h 还剩余多少时间 1h 遇到什么困难 没有困难 这两天解决的进度 ...
- 大数据JavaWeb之java基础巩固----Junit&反射&注解
最近打算从0开始学学大数据,目前的主业是Android开发,但是当年毕业之后其实是搞J2EE的,所以打算没事又来拓展一下后台的技能,扩宽一下自己的知识体系对于自己的未来也能够多一些可能,另外大数据的一 ...
- Tulip Festival(线段树+二分+CDQ+带修改莫队+树套树)
题目链接 传送门 线段树\(+\)二分思路 思路 比赛看到这题时感觉是一棵线段树\(+\)主席树,然后因为不会带修改主席树就放弃了,最后发现还卡了树套树. 由于本题数据保证序列中相同的数字不会超过20 ...
- steam相关插件
批量激活key:https://greasyfork.org/zh-CN/scripts/32718-steamredeemkeys 批量卖卡:https://github.com/Nuklon/St ...
- AD-logon workstation
默认AD登录到限制为64个 原因 发生此问题的原因是User-Workstations属性的Range-Upper值为1,024个字符.使用Active Directory用户和计算机输入NetBIO ...
- for循环:从键盘输入一个正整数n,
#include<stdio.h>void main(){ int i,n,sum=0; //声明三个整型变量,并为变量sum初始化赋值为0// printf("Please e ...
- [Algorithm] BFS vs DFS
//If you know a solution is not far from the root of the tree: BFS, because it is faster to get clos ...
- MongoDB TTL集合与固定集合
1.固定集合 MongoDB可以创建固定长度的集合,可以设置最大的集合空间或最大的集合数.创建集合的语法如下: db.createCollection("collection ...
- learning java 重定向标准输入输出
output redirectionOut: public class RedirectOut { public static void main(String[] args) throws File ...
- 在x64计算机上捕获32位进程的内存转储
这是一个我经常遇到的问题,我们经常会遇到这样的情况:我们必须重新捕获内存转储,因为内存转储是以“错误”的方式捕获的.简而言之:如果在64位计算机上执行32位进程,则需要使用允许创建32位转储的工具捕获 ...