HackerRank:将节点插入已排序的双向链表 - Kotlin

HackerRank: Inserting a Node Into a Sorted Doubly Linked List - Kotlin

只是想知道是否有人能够帮助我解决 Hackerrank 问题的 kotlin 实现 https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/problem

我得出以下解决方案,它只通过了 8 项测试中的 3 项。

我对自己做错了什么感到困惑,因为当我搜索互联网时,我找到了一个非常相似的 Java 解决方案 - https://www.geeksforgeeks.org/insert-value-sorted-way-sorted-doubly-linked-list/

任何帮助将不胜感激,我对此不知所措。

fun sortedInsert(llist: DoublyLinkedListNode?, data: Int): DoublyLinkedListNode? {
    val node = DoublyLinkedListNode(data)
    if (llist == null) return node
    
    if (llist.data >= data) {
        node.next = llist
        node.next!!.prev = node
        return node
    }
    
    var current = llist
    while (current?.next != null && current.next!!.data < data) {
        current = current.next
    }
    
    node.next = current?.next
    if (current?.next != null) current.next!!.prev = node
    
    node.prev = current
    current?.next = node
    
    return llist
}

HackerRank 的测试工具对于 Kotlin 似乎已损坏,缺少 println 来分隔每个测试用例的输出。一些通过(包括示例测试)的原因是这些 t=1,因此不会触发错误。

查看问题的discussion thread for more complaints about the issue. Some of the complaints go back 3 years as of December 2021, suggesting that this is not a high priority for HR to fix, if they're even aware of the issue. Furthermore, the problem appears to affect boilerplate in other linked list problems in Kotlin such as Reverse a Doubly Linked List

这是你的代码翻译成 Java 15,通过了 HackerRank 的判断:

public static DoublyLinkedListNode sortedInsert(
    DoublyLinkedListNode llist, int data
) {
    var node = new DoublyLinkedListNode(data);
    if (llist == null) return node;
    
    if (llist.data >= data) {
        node.next = llist;
        node.next.prev = node;
        return node;
    }
    
    var current = llist;
    while (current.next != null && current.next.data < data) {
        current = current.next;
    }
    
    node.next = current.next;
    if (current.next != null) current.next.prev = node;
    
    node.prev = current;
    current.next = node;
    return llist;
}