点击查看剑指Offer全解【Java & Golang】实现
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
思路
其实这就是链表的归并排序中的“合并”部分:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-wLB6HLu9-1573886800546)(http://note.youdao.com/yws/res/2348/32C7583868F34244A69B4248BC20B82C)]](https://i-blog.csdnimg.cn/blog_migrate/05da4bb550c4193dbe83141447d2f646.png)
具体的做法是定义两个指针a, b,分别指向需要合并的A链表和B链表的表头,其指向的节点分别表示微aNode和bNode,当aNode小于等于bNode时,将aNode放置在结果链表中,a向后走一位,反之bNode放置在结果链表中,b向后走一位。当aNode或bNode之一为空时,说明aNode或bNode中不为空的一方中的全部节点都大于已有的结果节点,那么将其放入结果节点的末尾即可。
Java实现
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if (list1 == null) {
return list2;
}
if (list2 == null) {
return list1;
}
ListNode res = new ListNode(-1);
ListNode head = res;
// 当list1和list2都不为空时
while (list1 != null && list2 != null) {
// 两两比较
if (list1.val <= list2.val) {
head.next = list1;
list1 = list1.next;
} else {
head.next = list2;
list2 = list2.next;
}
// 结果链表节点指向后一个节点
head = head.next;
}
// 当list1和list2中有一者为null。那么将不为null当那一方连接到结果链表中
if (list1 != null) {
head.next = list1;
}
if (list2 != null) {
head.next = list2;
}
return res.next;
}
}
Golang实现
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
var res *ListNode = &ListNode{-1, nil}
head := res
for l1 != nil && l2 != nil {
if l1.Val <= l2.Val {
head.Next = l1
l1 = l1.Next
} else {
head.Next = l2
l2 = l2.Next
}
head = head.Next
}
if l1 != nil {
head.Next = l1
}
if l2 != nil {
head.Next = l2
}
return res.Next
}

446



被折叠的 条评论
为什么被折叠?



