【问题标题】:I'm trying to answer Hackeranks data structure question and i don't know why this function fails我正在尝试回答 Hackerranks 数据结构问题,但我不知道为什么这个函数会失败
【发布时间】:2021-05-04 21:47:31
【问题描述】:

这是我在 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 上

【问题讨论】:

    标签: javascript data-structures singly-linked-list


    【解决方案1】:

    您的解决方案可能不适用于 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多