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,而是指向调用它的对象的环境。
本文详细介绍了如何使用JavaScript创建链表并实现数据插入,通过实例演示了如何获取链表中的特定元素。同时,深入探讨了在暴露链表头部时常见的错误做法及原因,帮助读者避免在实际开发中遇到相同的问题。
1484

被折叠的 条评论
为什么被折叠?



