获取js链表的head

1,创建链表,实现向链表中插入数据,以及返回链表的head;
function  ListNode(){
var   Node = function(value){
this.val = value;
this.next = null ;
}
var  head = null ;
var length = 0;
this.append = function(value){
 var  node = new Node(value);
if(head == null ){
 head  = node; 
}else{
var  current = head;
while(current.next){
current = current.next;
}
current.next = node;
}
length ++ ;
}

this.head = function(){
return head ;
}
}
2,然后测试一下,创建一个链表,然后向其中插入数据。然后返回这个链表的头,并打印出链表的第3个数字;
var  list = new ListNode();
list.append(1);
list.append(2);
list.append(3);
list.append(4);
var  list_head = list.head();
var num = 2,current =list_head;
while(num){
current =current.next;
num--;
}
console.log(current.val) ;  //3

3,这里需要讲一下,我们创建了链表以后,只有将链表的head暴露出去才能够使用,下面这种方式是错误的:

function  ListNode(){
var   Node = function(value){}
var  head = null ;
var length = 0;
this.append = function(value){} 
//此处并没有定义head();而是
this.head = head;
}
然后我们创建了list后,并append。此时想要获取第一个数字:
var  list_head = list.head;
console.log(list_head.val);  //undefied;
原因:var  list_head = list.head;这句话调用的this.head = head会在window全局环境下寻找head变量,发现找不到,所以是undefined,就是this的指向没有指向ListNode,而是指向调用它的对象的环境。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值