单向链表实现
链表让我们删除数据和新增数据更加方便!
head指针指向第一个存入的元素节点,每个节点都有next属性指向一下一个元素节点,最后一个元素的指针指向null
// 节点
class Node {
constructor(element) {
this.next = null;
this.element = element;
}
}
// 链表
class LinkList {
constructor() {
this.length = 0;
this.head = null;
}
// 新增一个节点
append(element) {
// 新建一个node
const node = new Node(element);
if (this.length === 0) {
this.head = node;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
this.length++;
}
inster(position, element) {
if (position >= 0 && position < this.length) {
const node = new Node(element);
if (position === 0) {
node.next = this.head;
this.head = node;
} else {
let current = this.head;
let index = 0;
let per = null;
while (index++ < position) {
per = current;
current = current.next;
}
node.next = current;
per.next = node;
}
this.length++;
}
}
removeAt(position) {
if (position >= 0 && position < this.length) {
if (position === 0) {
this.head = this.head.next;
} else {
let current = this.head;
let index = 0;
let per = null;
while (index++ < position) {
per = current;
current = current.next;
}
per.next = current.next;
}
this.length--;
}
}
update(postion, element) {
if (postion >= 0 && postion < this.length) {
if (postion === 0) {
this.head.element = element;
} else {
let current = this.head;
let index = 0;
while (index++ < position) {
current = current.next;
}
current.element = element;
}
}
}
}
// 调用
const linkList = new LinkList();
// 新增节点
linkList.append("1");
linkList.append("2");
linkList.append("3");
console.log(linkList);
// {
// length: 3,
// head: {
// next: {
// next: {
// next: null,
// element: "3",
// },
// element: "2",
// },
// element: "1",
// },
// }
// 插入
linkList.inster(1, "4");
console.log(linkList);
// {
// length: 4,
// head: {
// next: {
// next: {
// next: {
// next: null,
// element: "3",
// },
// element: "2",
// },
// element: "4",
// },
// element: "1",
// },
// }
// 删除位置1
linkList.removeAt(1);
// {
// length: 3,
// head: {
// next: {
// next: {
// next: null,
// element: "3",
// },
// element: "2",
// },
// element: "1",
// },
// }
// 更新数据
linkList.update(0, "5");
// {
// length: 3,
// head: {
// next: {
// next: {
// next: null,
// element: "3",
// },
// element: "2",
// },
// element: "5",
// },
// }