这是有上期,没下期,学习看心情,更新看随机的老王的学习笔记,好好看,没有下期了……
链表中的方法有:插入节点,找到最后一个节点,找到某个节点,找到某个节点的前一个节点,删除节点,在某个节点之后插入节点,在某个节点之前插入节点,遍历。
function Node(element) {
this.element = element;
this.next = null;
}
function LList() {
this.head = new Node("head");
this.insert=function (data) {
//this.head.next = new Node(data);
//创建新的节点
var buffer = new Node(data);
//获得最后的节点
var last = this.findLast();
//把最后节点的next指向新节点
last.next = buffer;
}
//找到最后节点
this.findLast=function () {
var buffer = this.head;
while(buffer.next!=null){
buffer = buffer.next;
}
return buffer;
}
//遍历
this.forEach=function (call) {
var buffer = this.head;
while(buffer!=null){
call(buffer);
buffer = buffer.next;
}
}
//找到某个节点
this.find=function (data) {
var buffer = this.head;
while(buffer!=null){
if(buffer.element==data){
return buffer;
}
buffer = buffer.next;
}
return buffer;
}
//找到某个节点的前一个节点
this.findPrevious=function (data) {
var buffer = this.head;
var node=null;
while(buffer!=null&&buffer.next!=null){
//如果它的下一个节点的元素等于data
//那么这个节点就是要找的节点的上一个节点
if(buffer.next.element==data){
node = buffer;
return node;
}
buffer = buffer.next;
}
return node;
}
//删除节点
this.remove=function (data) {
let nextNode = this.find(data).next;
let preNode = this.findPrevious(data);
preNode.next = nextNode;
}
//在某个节点之后插入节点
this.insertAfter=function (element,after) {
//创建当前的节点
let node = new Node(element);
//获得after节点
let afterNode = this.find(after);
//afterNode的后面节点和当前节点
node.next = afterNode.next;
afterNode.next = node;
}
//在某个节点之前插入节点
this.insertBefore=function (element,before) {
//创建当前的节点
let node = new Node(element);
//获得before节点的前一个节点
let preNode = this.findPrevious(before);
//把before节点连到新节点的后面
node.next = preNode.next;
//把preNode节点和新节点连在一起
preNode.next = node;
}
}
测试:
let lList = new LList();
lList.insert("你");
lList.insert("有");
lList.insert("病");
lList.insert("啊");
lList.insert("1");
lList.insert("2");
lList.insert("3");
lList.insert("4");
lList.insert("5");
lList.insert("6");
console.log(lList.findLast());
console.log(lList.find("1"));
console.log(lList.findPrevious("3"));
lList.remove("6");
lList.insertAfter("aaa","1");
lList.insertBefore("aaa","4");
lList.forEach(function (node) {
console.log(node.element);
});
结果: