[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 ...
随机推荐
- php的希尔排序
算是改进了的插入排序, 从性能时间上来看,也确实更有改进. 但比起php内置的功能,性能还有十倍之差呢 <?php /** * 原理:把排序的数据根据增量分成几个子序列,对子序列进行插入排序, ...
- P2602 [ZJOI2010]数字计数(递推)
P2602 [ZJOI2010]数字计数 思路: 首先考虑含有前导0的情况,可以发现在相同的\(i\)位数中,每个数的出现次数都是相等的.所以我们可以设\(f(i)\)为\(i\)位数每个数的出现次数 ...
- sql中如何获取一条数据中所有字段的名称和值
declare ) ) --获取表的列名 ,),filename INTO #templist FROM (select cl.name as filename from sys.tables AS ...
- *arg和**kwarg作用
*args:可以理解为只有一列的表格,长度不固定. **kwargs:可以理解为字典,长度也不固定. 1.函数调用里的*arg和**kwarg: (1) *arg:元组或列表 ...
- KM模板 最大权匹配(广搜版) Luogu P1559 运动员最佳匹配问题
KM板题: #include <bits/stdc++.h> using namespace std; inline void read(int &num) { char ch; ...
- 使用docker来创建一个etcd集群
docker run -d --name etcd1 --network etcdnet --ip 172.25.0.101 -p 23791:2379 -e ETCDCTL_API=3 -v /ro ...
- Nodejs仿Apache的部分功能
一.初步实现Apache的部分功能 //1.加载模块 var http=require('http'); var fs=require('fs'); //2.创建server var server=h ...
- HTML Meta标签和link标签
一.meta 标签 name属性主要用于描述网页,对应于content(网页内容) 1.<meta name="Generator" contect="" ...
- SDSC2019【游记】
目录 SDSC2019 游记 Day0 Day 1 Day2 Day3 Day4 Day5 Day6 Day 7 Day8 SDSC2019 游记 Day0 这次夏令营在日照某大学举行,我很想夸一夸喷 ...
- java如何判断溢出
public int reverse2(int x) { double ans=0; int flag=1; if(x<0){ flag=-1; } x=x*flag; while(x>0 ...