繁体   English   中英

我正在尝试回答 Hackerranks 数据结构问题,但我不知道为什么这个 function 会失败

[英]I'm trying to answer Hackeranks data structure question and i don't know why this function fails

这是 Javascript 中的问题和我的解决方案

您将获得指向链表头节点的指针和要添加到链表的 integer。 使用给定的 integer 创建一个新节点。 将该节点插入到链表的尾部,并返回插入该新节点后形成的链表的头节点。 给定的头指针可能是 null,这意味着初始列表为空。

// Complete the insertNodeAtTail function below.

/*
 * For your reference:
 *
 * SinglyLinkedListNode {
 *     int data;
 *     SinglyLinkedListNode next;
 * }
 *
 */
function insertNodeAtTail(head, data) {

    if(!head) return;
    
    let currentNode = head;
    while(currentNode.next){
        currentNode = currentNode.next
        
    }
    const newNode = new SinglyLinkedListNode(data)
    currentNode.next = newNode
    
    return head

解决方案是在我的 vscode 上工作,而不是在hackerrank 上

您的解决方案可能不适用于边缘情况,其中头部为 NULL。 试试这个解决方案:

if(!head)
{
    const newNode = new SinglyLinkedListNode(data);
    return newNode;
}


let currentNode = head;
while(currentNode.next){
    currentNode = currentNode.next
    
}
const newNode = new SinglyLinkedListNode(data)
currentNode.next = newNode

return head

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM