1.创建一个单节点:
var firstNode = {
data : 12,
next : null
};
2.通过第一个单节点的next属性可以链接到另一个单节点从而构成一个链表。
firstNode.next = {
data : 24,
next : null
};
//也就是
var LinkedList = {
data : 12,
next : {
data : 24,
next : null
}
};
3.接下来可以为链表添加一些方法,如:在原链表最后加入一个新的节点,去掉原链表中的某个节点等等。
function LinkedList(){
this.length = 0;
this.head = null;
}
LinkedList.prototype = {
add: function(data){
var node = {
data: data,
next : null
};
//特殊情况,原链表为空
if(!this.head){
this.head = node;
}else{
current = this.head;
while(current.next){
current = current.next;
}
current.next = node;
}
this.length++;
},
item: function(index){
if(index > -1 && index < this.length){
var current = this.head,
i = 0;
while(i++ < index){
current = current.next;
}
return current.data;
}else{
return null;
}
},
remove: function(index){
if(index > -1 && index < this.length){
var current = this.head,
previous,
i = 0;
//特殊情况:想要移除为首节点
if(index === 0){
this.head = current.next;
}else{
while(i++ < index){
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.length--;
return current.data;
}else{
return null;
}
}
}
参考:
1.Computer science in JavaScript: Linked list
https://www.nczonline.net/blog/2009/04/13/computer-science-in-javascript-linked-list/
2.What is the ‘head’ of a linked list?
https://stackoverflow.com/questions/4973713/what-is-the-head-of-a-linked-list
3.JavaScript 版数据结构与算法(三)链表
https://lewis617.github.io/2017/02/15/linked-list/