标签:基础知识 过程 max ber 通过 etc rip return tco
Difficulty: Easy
Related Topics: Linked List
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
合并两个有序的链表,返回合并后的链表。新链表应该是通过重组前面链表的节点构成。
Input: l1 = [1,2,4], l2 = [1,3,4]
Output: [1,1,2,3,4,4]
Input: l1 = [], l2 = []
Output: []
Input: l1 = [], l2 = [0]
Output: [0]
The number of nodes in both lists is in the range [0, 50]
.
两个链表的节点数量在 [0, 50]
之间
-100 <= Node.val <= 100
Both l1
and l2
are sorted in non-decreasing order.
两个链表以非递减顺序排序
合并单链表也是数据结构课的基础知识了,具体实现过程不再赘述。先给出复制节点值的方法(当然,此法不符合题目要求,不过对于我而言,这种方法更直观一点),代码如下:
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
if (l1 == null && l2 == null) {
return null
}
val dummyHead = ListNode(-1)
var i: ListNode? = dummyHead
var p = l1
var q = l2
while (!(p == null && q == null)) {
val leftVal = p?.`val`?:Int.MAX_VALUE
val rightVal = q?.`val`?:Int.MAX_VALUE
if (leftVal < rightVal) {
i?.next = ListNode(leftVal)
i = i?.next
p = p?.next
} else {
i?.next = ListNode(rightVal)
i = i?.next
q = q?.next
}
}
val result = dummyHead.next
dummyHead.next = null
return result
}
}
然后再给一种直接对节点进行操作的方法(来自于我看的一本算法书,原始代码为 Java 实现,我改为用 Kotlin 实现):
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
if (l1 == null || l2 == null) {
return l1 ?: l2
}
val head = if (l1.`val` < l2.`val`) l1 else l2
var cur1: ListNode? = if (head === l1) l1 else l2
var cur2: ListNode? = if (head === l1) l2 else l1
var pre: ListNode? = null
while (cur1 != null && cur2 != null) {
if (cur1.`val` <= cur2.`val`) {
pre = cur1
cur1 = cur1.next
} else {
val next = cur2.next
pre?.next = cur2
cur2.next = cur1
pre = cur2
cur2 = next
}
}
pre?.next = cur1 ?: cur2
return head
}
}
[LeetCode] 21. Merge Two Sorted Lists(合并两个有序链表)
标签:基础知识 过程 max ber 通过 etc rip return tco
原文地址:https://www.cnblogs.com/zhongju/p/13800865.html