简体   繁体   中英

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

This is the question and my solution in Javascript

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty.

// 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

The solution, is working on my vscode but not on hackerrank

Your solution may be not working for edge case, where head is NULL. Try this solution:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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