首页 > 解决方案 > 如何在 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 中也能完美运行。可能是什么问题?

标签: pythonalgorithmkotlindata-structureslinked-list

解决方案


此代码以递归方式反转单个链表:

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()
}

推荐阅读