由函数定义的变量
我正在做这个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
}