Javascript I';我试图回答数据结构问题,但我不';我不知道为什么这个功能失败

Javascript I';我试图回答数据结构问题,但我不';我不知道为什么这个功能失败,javascript,data-structures,singly-linked-list,Javascript,Data Structures,Singly Linked List,这就是我在Javascript中的问题和解决方案 您将获得指向链接列表的头节点的指针和要添加到列表中的整数。使用给定的整数创建一个新节点。在链表的尾部插入此节点,并返回插入此新节点后形成的链表的头节点。给定的头指针可能为空,这意味着初始列表为空 // Complete the insertNodeAtTail function below. /* * For your reference: * * SinglyLinkedListNode { * int data; *

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

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

// 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上不工作

您的解决方案可能不适用于head为NULL的edge情况。尝试以下解决方案:

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