python - 如何在 Kotlin 中正确反转链表?
问题描述
我已经完成了 Hackerrank 和 Leetcode 反向 LinkedList 问题,并且我下面的代码在 Leetcode 中完美运行,通过了所有测试用例,但在黑客等级中失败了一些测试用例。用 python 或 C++ 编写的相同代码通过了所有黑客级别的测试用例。可能是什么问题?
Kotlin 代码是
if (head == null) return head
var new_head = head
var next_node = new_head.next
while (next_node != null) {
val temp = next_node.next
next_node.next = new_head
new_head = next_node
next_node = temp
}
head.next = null
return new_head
它在 Leetcode 中完美运行,而不是在 Hacker Rank 中。以下是在 Hacker Rank 中完美运行的 Python 版本。Python 代码与 Kotlin 代码相同。
if head is None:
return None
else:
new_head = head
next_node = new_head.next
while next_node != None:
temp_node = next_node.next
next_node.next = new_head
new_head = next_node
next_node = temp_node
head.next = None
return new_head
用 C++ 编写的相同代码在 Hacker Rank 中也能完美运行。可能是什么问题?
解决方案
此代码以递归方式反转单个链表:
data class ReverseInRecursive(
var head: Node? = null)
{
data class Node(var data: Int, var next: Node? = null)
fun reverse(head: Node?): Node?
{
if (head?.next == null)
return head
val rest = reverse(head.next)
head.next!!.next = head
head.next = null
return rest
}
fun print()
{
var temp = head
while (temp != null)
{
print("${temp.data} ")
temp = temp.next
}
}
fun push(data: Int)
{
var newNode = Node(data)
if (head == null)
{
head = newNode
return
}
var temp = head
while (temp?.next != null)
{
temp = temp.next
}
temp?.next = newNode
}
}
fun main()
{
var reverseInRecursive = ReverseInRecursive()
reverseInRecursive.push(1)
reverseInRecursive.push(2)
reverseInRecursive.push(3)
reverseInRecursive.push(4)
reverseInRecursive.head =
reverseInRecursive.reverse(reverseInRecursive.head)
reverseInRecursive.print()
}
推荐阅读
- sql - 如何按时间使用 Dense_rank() 顺序但忽略来自另一个列的重复项?
- monaco-editor - 未能添加新的摩纳哥语言;不知道我错过了什么
- oracle-adf - 在哪里检查它加载的 weblogic 服务器 xmlbeans 版本以及如何指向自定义 lib 版本?
- twitter - 如何获取带有链接或 url 链接的推文?
- javascript - 如何使用谷歌应用脚本在 gsheets 中自动填充公式
- ubuntu - E:存储库“http://ppa.launchpad.net/mc3man/xerus-media/ubuntu focus Release”没有发布文件
- javascript - 在高图中寻找自定义散点图
- node.js - Node+ExpressRouter -> CommonJS 到 ESM --> 导入路由 --> 错误 [ERR_MODULE_NOT_FOUND]: 找不到模块
- github - Github 分支保护规则,设置分支名称的模式
- adonis.js - Adonsjs 4 - 什么是 use() 以及为什么它在版本 5 中不起作用