function Node(value){
this.value = value;
this.next = null;
}
var a = new Node("a");
var b = new Node("b");
var c = new Node("c");
var d = new Node("d");
a.next = b;
b.next = c;
c.next = d;
现在的结构是这样的
需要说明的是,链表的每一个都可以当作根节点
这就是一个链表了,下面来写一些相关函数
遍历打印
获取链表的长度
通过下标获取链表中的某个数据
通过下标设置链表中的某个数据
在链表某一个节点之后加入一个新节点
在链表末尾加入一个新节点
删除一个链表节点
链表倒序
1.遍历打印
functionprint(root){
//分治法
if(root){
console.log(root.value); //打印自己
print(root.next);
}
}
print(a); 把a给它,输出 a b c d
2.获取链表的长度
function count(root){
if(!root) return 0;
return 1 + count(root.next);
}
var len = count(a); 输出4
3.通过下标获取链表中的某个数据
function getNode(root,index){
/**
* 判断某个节点是否是我要查找的节点
* @param {*} node 表示某个节点
* @param {*} i 该节点是第几个节点
*/
function _getNode(node,i){
if(!node) return null;
if(i === index) return node.value;
return _getNode(node.next,++i);
}
return _getNode(root,0);
}
var nd = getNode(a,2);
console.log(nd);// c