21. 合并两个有序链表 - 力扣(LeetCode)
题目描述
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
解题思路
合并两个有序列表。当两个链表有一个为空时,直接返回另一个链表。通过遍历比较两个链表,将较小的节点放入新链表中,最后返回新链表,直到有一个链表为空。
遍历结束后,判断两个链表是否为空,将不为空的链表中的节点插入新的链表中。
java
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null) return list2;
if (list2 == null) return list1;
ListNode newNode = new ListNode(-1);
ListNode retNode = newNode;
while (list1 != null && list2 != null) {
if (list1.val < list2.val) {
newNode.next = new ListNode(list1.val);
list1 = list1.next;
} else {
newNode.next = new ListNode(list2.val);
list2 = list2.next;
}
newNode = newNode.next;
}
if (list1 != null) {
newNode.next = list1;
}
if (list2 != null) {
newNode.next = list2;
}
return retNode.next;
}
}
kotlin
class Solution {
fun mergeTwoLists(list1: ListNode?, list2: ListNode?): ListNode? {
if (list1 == null) return list2
if (list2 == null) return list1
var l1 = list1
var l2 = list2
var newListNode = ListNode(-1)
val retListNode = newListNode
while (l1 != null && l2 != null) {
if (l1!!.`val` < l2!!.`val`) {
newListNode.next = ListNode(l1.`val`)
l1 = l1.next
} else {
newListNode.next = ListNode(l2.`val`)
l2 = l2.next
}
newListNode = newListNode.next
}
l1?.let {
newListNode.next = it
}
l2?.let {
newListNode.next = it
}
return retListNode.next
}
}
go
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
if list1 == nil {
return list2
}
if list2 == nil {
return list1
}
newNode := new(ListNode)
retNode := newNode
for {
if list1.Val < list2.Val {
newNode.Next = &ListNode{
Val: list1.Val,
Next: nil,
}
list1 = list1.Next
} else {
newNode.Next = &ListNode{
Val: list2.Val,
Next: nil,
}
list2 = list2.Next
}
newNode = newNode.Next
if list1 == nil || list2 == nil {
break
}
}
if list1 != nil {
newNode.Next = list1
}
if list2 != nil {
newNode.Next = list2
}
return retNode.Next
}