1. 题目
描述
输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。数据范围:10000≤n≤1000,−1000≤节点值≤1000
要求:空间复杂度 O(1),时间复杂度 O(n)如输入{1,3,5},{2,4,6}时,合并后的链表为{1,2,3,4,5,6},所以对应的输出为{1,2,3,4,5,6},转换过程如下图所示:
或输入{-1,2,4},{1,3,4}时,合并后的链表为{-1,1,2,3,4,4},所以对应的输出为{-1,1,2,3,4,4},转换过程如下图所示:
示例1
输入:
{1,3,5},{2,4,6}
返回值:
{1,2,3,4,5,6}
示例2
输入:
{},{}
返回值:
{}
示例3
输入:
{-1,2,4},{1,3,4}
返回值:
{-1,1,2,3,4,4}
2. 解题思路
假如要合并的两个链表分别为: 1→3→5与 2→4→6,对他们两个链表合并,合并之后的链表为: 1→2→3→4→5→6。结构如下图所示。
第一步:定义临时虚拟头节点与指针变量。指针变量有3个,cur用于操作的链表,h1用于链表1节点值的对比,h2用于链表2节点值的对比。
第二步:循环合并两个链表。
首先比较h1与h2指向节点的值,这时1<2,cur指向值小的链表节点1,h1再后移一个位置,如下图所示:
接下来再更改cur节点的指针域的指向,原来指向3节点,现在让它指向h2对应的节点。更改完之后需要移动cur、h2指针变量。如下图所示:
再来比较h1与h2指向节点的值,此时3<4,需要让cur指向h1对应的节点(值为3的节点)。更改完之后需要移动cur、h1(cur移动到它的下一节点,h1移动到它的下一个节点)。如下图所示:
再来比较h1与h2所指向的节点值,此时:4<5。cur指向较小值的节点4,之后再移动cur、h2到它们的下一个节点,如图所示:
再来比较h1与h2指向节点的值,此时5<6。需要让cur指向5节点,之后再移动cur、h1到它们的下一个节点,如图所示:
此时,h1已经指向Null了,循环结束。
第三步:链接剩余链表节点。
由于h1已经指向Null了,这时只需要将cur指向h2就可以,如下图所示:
此时链表的合并已经完成。
第四步:返回头节点。
链表的头结点为虚拟头结点tmpHead的下一个节点,直接返回即可。
如果文字描述的不太清楚,你可以参考视频的详细讲解。
- Python版本:https://www.bilibili.com/cheese/play/ep1370260
- Java版本:https://www.bilibili.com/cheese/play/ep1366716
- Golang版本:https://www.bilibili.com/cheese/play/ep1364393
3. 编码实现
3.1 Python编码实现
class ListNode:
def __init__(self, x):
self.val = x # 链表的数值域
self.next = None # 链表的指针域
# 从链表节点尾部添加节点
def insert_node(node, value):
if node is None:
print("node is None")
return
# 创建一个新节点
new_node = ListNode(value)
cur = node
# 找到链表的末尾节点
while cur.next is not None:
cur = cur.next
# 末尾节点的next指针域连接新节点
cur.next = new_node
# 打印链表(从链表头结点开始打印链表的值)
def print_node(node):
cur = node
# 遍历每一个节点
while cur is not None:
print(cur.val, end="\t")
cur = cur.next # 更改指针变量的指向
print()
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pHead1 ListNode类
# @param pHead2 ListNode类
# @return ListNode类
#
class Solution:
def Merge(self, pHead1: ListNode, pHead2: ListNode) -> ListNode:
# 1.定义临时虚拟头节点与指针变量
tmp_head = ListNode(-1)
cur = tmp_head
p1 = pHead1 # 为了便于理解,定义了h1、h2临时指针变量,其实可以直接用 pHead1、pHead2
p2 = pHead2
# 2.循环合并两个链表
while p1 is not None and p2 is not None:
# 2.1 cur指针域链接值较小的链表节点,并移动较小值节点的指针变量
if p1.val <= p2.val:
cur.next = p1
p1 = p1.next
else:
cur.next = p2
p2 = p2.next
cur = cur.next
# 3. 链接剩余链表节点
if p1 is not None:
cur.next = p1
else:
cur.next = p2
# 4. 返回头节点
return tmp_head.next
if __name__ == '__main__':
root1 = ListNode(1)
insert_node(root1, 3)
insert_node(root1, 5)
root2 = ListNode(2)
insert_node(root2, 4)
insert_node(root2, 6)
print_node(root1)
print_node(root2)
s = Solution()
head = s.Merge(root1, root2)
print_node(head)
3.2 Java编码实现
package LL04;
public class Main {
//定义链表节点
static class ListNode {
private int val; //链表的数值域
private ListNode next; //链表的指针域
public ListNode(int data) {
this.val = data;
this.next = null;
}
}
//添加链表节点
private static void insertNode(ListNode node, int data) {
if (node == null) {
return;
}
//创建一个新节点
ListNode newNode = new ListNode(data);
ListNode cur = node;
//找到链表的末尾节点
while (cur.next != null) {
cur = cur.next;
}
//末尾节点的next指针域连接新节点
cur.next = newNode;
}
//打印链表(从头节点开始打印链表的每一个节点)
private static void printNode(ListNode node) {
ListNode cur = node;
//遍历每一个节点
while (cur != null) {
System.out.print(cur.val + "\t");
cur = cur.next; //更改指针变量的指向
}
System.out.println();
}
public static class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
public ListNode Merge(ListNode pHead1, ListNode pHead2) {
// write code here
// 1.定义临时虚拟头节点与指针变量
ListNode tmpHead = new ListNode(-1);
ListNode cur = tmpHead;
ListNode h1 = pHead1; //为了便于理解,定义了h1、h2临时变量,其实可以直接用 pHead1、pHead2
ListNode h2 = pHead2;
// 2.循环合并两个链表
while (h1 != null && h2 != null) {
// 2.1 cur指针域链接值较小的链表节点,并移动较小值节点的指针变量
if (h1.val <= h2.val) {
cur.next = h1;
h1 = h1.next;
} else {
cur.next = h2;
h2 = h2.next;
}
// 2.2 移动cur指针变量
cur = cur.next;
}
// 3.链接剩余链表节点
if (h1 != null) {
cur.next = h1;
} else {
cur.next = h2;
}
// 4.返回头节点
return tmpHead.next;
}
}
public static void main(String[] args) {
ListNode root1 = new ListNode(1);
insertNode(root1, 3);
insertNode(root1, 5);
ListNode root2 = new ListNode(2);
insertNode(root2, 4);
insertNode(root2, 6);
printNode(root1);
printNode(root2);
Solution solution = new Solution();
ListNode head = solution.Merge(root1, root2);
printNode(head);
}
}
3.3 Golang编码实现
package main
import "fmt"
// ListNode 定义链表节点
type ListNode struct {
Val int //链表的数值域
Next *ListNode //链表的指针域
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
func Merge(pHead1 *ListNode, pHead2 *ListNode) *ListNode {
// write code here
// 1.定义临时虚拟头节点与指针变量
tmpHead := &ListNode{Val: -1}
cur := tmpHead
h1 := pHead1 //为了便于理解,定义了h1、h2临时指针变量,其实可以直接用 pHead1、pHead2
h2 := pHead2
// 2.循环合并两个链表
for h1 != nil && h2 != nil {
// 2.1 cur指针域链接值较小的链表节点,并移动较小值节点的指针变量
if h1.Val <= h2.Val {
cur.Next = h1
h1 = h1.Next
} else {
cur.Next = h2
h2 = h2.Next
}
// 2.2 移动cur指针变量
cur = cur.Next
}
// 3.链接剩余链表节点
if h1 != nil {
cur.Next = h1
} else {
cur.Next = h2
}
// 4.返回头节点
return tmpHead.Next
}
func main() {
root1 := &ListNode{Val: 1}
root1.Insert(3)
root1.Insert(5)
root1.Print()
root2 := &ListNode{Val: 2}
root2.Insert(4)
root2.Insert(6)
root2.Print()
head := Merge(root1, root2)
head.Print()
}
// Insert 从链表节点尾部添加节点
func (ln *ListNode) Insert(val int) {
if ln == nil {
return
}
//创建一个新节点
newNode := &ListNode{Val: val}
cur := ln
//找到链表的末尾节点
for cur.Next != nil {
cur = cur.Next
}
//末尾节点的next指针域连接新节点
cur.Next = newNode
}
// Print 从链表头结点开始打印链表的值
func (ln *ListNode) Print() {
if ln == nil {
return
}
cur := ln
//遍历每一个节点
for cur != nil {
fmt.Print(cur.Val, "\t")
cur = cur.Next //更改指针变量的指向
}
fmt.Println()
}
<font color=#f00>如果上面的代码理解的不是很清楚,你可以参考视频的详细讲解。</font>
- Python编码:https://www.bilibili.com/cheese/play/ep1370260
- Java编码:https://www.bilibili.com/cheese/play/ep1366716
- Golang编码:https://www.bilibili.com/cheese/play/ep1364393
4.小结
合并两个有序的链表,可以通过:定义临时虚拟头节点与指针变量、循环合并两个链表、链接剩余链表节点和返回头节点4步来完成,本题的难点在于思路,即想到用虚拟头结点tmpHead、操作节点cur、链表1与链表2值比较节点h1、h2。
更多算法视频讲解,你可以从以下地址找到:
- Python编码实现:https://www.bilibili.com/cheese/play/ep1509965
- Java编码实现:https://www.bilibili.com/cheese/play/ep1510007
- Golang编码实现:https://www.bilibili.com/cheese/play/ep1509945
对于链表的相关操作,我们总结了一套【可视化+图解】方法,依据此方法来解决链表相关问题,链表操作变得易于理解,写出来的代码可读性高也不容易出错。具体也可以参考视频详细讲解。
今日佳句:身无彩凤双飞翼,心有灵犀一点通。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。