1、链表是一组节点组成的集合。每个节点都使用一个对象的引用指向它的后继。指向另一个节点的引用叫做链
链表分为:单向链表,双向链表,以及循环链表
1.1、节点
节点由两部分组成:一部分是节点数据,一部分是指向下一个节点的指针区域
/**
* 节点基类
*/
function Node(data) {
this.data = data; // 当前节点数据
this.next = null; // 指向下一节点的指针
}
// 定义节点
let node1 = new Node('节点1');
let node2 = new Node('节点2');
let node3 = new Node('节点3');
node1.next = node2;
node2.next = node3;
2、链表
/**
* 节点基类
*/
function Node(data) {
this.data = data; // 当前节点数据
this.next = null; // 指向下一节点的指针
}
function LinkList() {
this.head = new Node('head'); // 默认有头节点
this.length = 0; // 链表长度
}
LinkList.prototype = {
// 查找某个节点
find: function (item) {
let currentNode = this.head;
/**
* 从手节点遍历依次比较,如果当前节点不是,就把下一个节点赋值给currentNoder
*/
while (currentNode.data !== item) {
currentNode = currentNode.next;
}
return currentNode;
},
// 向指定元素后插入新节点
insertAfter: function (newElement, item) {
// 创建要插入的新节点
let newNode = new Node(newElement);
// 当前节点
let currentNode = this.find(item);
// 把当前节点 指向下一个节点的指针赋值给新节点
newNode.next = currentNode.next;
// 更新当前节点的指针,重新指向新节点
currentNode.next = newNode;
this.length++;
},
// 查找某节点的前一个节点
findBefore: function (item) {
// 头节点
let currentNode = this.head;
// 从头节点开始遍历 如果节点指针指向的节点的数据和传入数据不同,
// 就把下一个节点赋值给currentNode 继续遍历下去
while (currentNode.next?.data !== item) {
currentNode = currentNode.next;
}
return currentNode;
},
// 删除节点
delete: function (item) {
// 找到要删除节点的之前一个节点
let preNode = this.findBefore(item);
preNode.next = preNode.next.next;
this.length--;
},
// 修改指定节点
edit: function (item, newData) {
let currentNode = this.find(item);
currentNode.data = newData;
},
// 显示
display: function () {
let currentNode = this.head;
while (currentNode.next !=== null) {
console.log(currentNode);
currentNode = currentNode.next;
}
},
};
3、测试--添加节点
const myLinkList = new LinkList();
myLinkList.insertAfter('节点1', 'head');
myLinkList.insertAfter('节点2', '节点1');
myLinkList.insertAfter('节点3', '节点2');
3.1、测试--查找节点
myLinkList.find('节点1')
3.2、测试--删除节点
myLinkList.delete('节点1')