LeetCode之Merge In Between Linked
2020-12-22 本文已影响0人
糕冷羊
问题:
方法:
第一步,遍历list1,通过序号获取a对应的节点和b对应的节点;第二步,遍历list2获取尾部节点,然后把list2的头部接到a节点后,把b节点接到list2的尾部,最后返回list1的头部节点即可。
class MergeInBetweenLinkedLists {
fun mergeInBetween(list1: ListNode?, a: Int, b: Int, list2: ListNode?): ListNode? {
var aNode: ListNode? = null
var bNode: ListNode? = null
var index = 0
var cur = list1
while (cur != null) {
if (index == a - 1) {
aNode = cur
}
if (index == b + 1) {
bNode = cur
}
cur = cur.next
index++
}
aNode?.next = list2
cur = list2
while (cur?.next != null) {
cur = cur.next
}
cur?.next = bNode
return list1
}
}
fun main() {
}
有问题随时沟通