我正在尝试回答 Hackeranks 数据结构问题,但我不知道为什么此功能会失败
I'm trying to answer Hackeranks data structure question and i don't know why this function fails
这是问题和我在Javascript
中的解决方案
你得到了指向链表头节点的指针和一个要添加到链表中的整数。使用给定的整数创建一个新节点。将这个节点插入到链表的尾部,return插入这个新节点后形成的链表的头节点。给定的头指针可能为空,这意味着初始列表为空。
// 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 的边缘情况。试试这个解决方案:
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
这是问题和我在Javascript
中的解决方案你得到了指向链表头节点的指针和一个要添加到链表中的整数。使用给定的整数创建一个新节点。将这个节点插入到链表的尾部,return插入这个新节点后形成的链表的头节点。给定的头指针可能为空,这意味着初始列表为空。
// 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 的边缘情况。试试这个解决方案:
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