最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

由函数定义的变量

IT培训 admin 4浏览 0评论

由函数定义的变量

我正在做这个Hackerrank challange this的问题是:

Input格式:

你必须完成Node* Insert(Node* head, int data)方法。它需要两个参数:链表的头部和要插入的整数。你不应该从input / console读取任何stdin

Output格式:

在尾部插入新节点,只需将return插入更新链接列表的头部。不要向stdout / console打印任何东西。

/*
  Node is defined as
  var Node = function(data) {
      this.data = data;
      this.next = null;
  }
*/

这是我的代码:

function insert(head, data) {
    if(head){
        while(head.next!==null){
            head = head.next;
        }
        head.next = Node(data);

    }else{
        head = Node(data);
    }
}

有人知道为什么它是错的或者可以帮助我理解它是如何工作的吗?

回答如下:

你应该返回一些东西,你的代码应该是这样的:

function(head, data) {
  if (head) {
    var nextNode = head

    while (nextNode.next !== null) {
      nextNode = nextNode.next
    }

    nextNode.next = new Node(data)
  } else {
    head = new Node(data)
  }

  return head
}

由函数定义的变量

我正在做这个Hackerrank challange this的问题是:

Input格式:

你必须完成Node* Insert(Node* head, int data)方法。它需要两个参数:链表的头部和要插入的整数。你不应该从input / console读取任何stdin

Output格式:

在尾部插入新节点,只需将return插入更新链接列表的头部。不要向stdout / console打印任何东西。

/*
  Node is defined as
  var Node = function(data) {
      this.data = data;
      this.next = null;
  }
*/

这是我的代码:

function insert(head, data) {
    if(head){
        while(head.next!==null){
            head = head.next;
        }
        head.next = Node(data);

    }else{
        head = Node(data);
    }
}

有人知道为什么它是错的或者可以帮助我理解它是如何工作的吗?

回答如下:

你应该返回一些东西,你的代码应该是这样的:

function(head, data) {
  if (head) {
    var nextNode = head

    while (nextNode.next !== null) {
      nextNode = nextNode.next
    }

    nextNode.next = new Node(data)
  } else {
    head = new Node(data)
  }

  return head
}

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论