我只是学习了链表的数据结构。
我的问题很简单:如何克隆链接列表?
(返回头不是克隆。)
这是我的尝试,但结果不好。
(例如输入(1,2,3,4,5)输出(1,5)
我该如何解决。
class ListNode(var `val`: Int) {
var next: ListNode? = null
}
fun cloneLiskedList(head: ListNode?): ListNode? {
if (head == null) {
return null
}
val answer = ListNode(head.`val`)
var tempListNode: ListNode ?= null
var headPoint = head.next
while (headPoint != null) {
val listNode = ListNode(headPoint.`val`)
tempListNode = listNode
tempListNode.next = listNode
headPoint = headPoint.next
}
answer.next = tempListNode
return answer
}
输入(1,2,3,4,5)输出(1,5)//预期(1,2,3,4,5)
最佳答案
以下应该工作
fun cloneLiskedList(head: ListNode?): ListNode? {
if (head == null) {
return null
}
val answer = ListNode(head.`val`)
var tempListNode: ListNode? = answer
var headPoint = head.next
while (headPoint != null) {
tempListNode?.next = ListNode(headPoint.`val`)
headPoint = headPoint.next
tempListNode = tempListNode?.next
}
return answer
}
关于algorithm - 如何用Kotlin克隆链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63734763/