class Node {
constructor(element) {
this.element = element;
this.next = undefined;
}
}
function defaultEquals(a, b) {
return a === b;
}
// 模拟链表类
class LinkedList {
constructor(equalsFn = defaultEquals) {
this.count = 0;
this.head = undefined;
this.equalsFn = equalsFn;
}
size() {
return this.count
}
isEmpty() {
return this.count === 0
}
getHead() {
return this.head;
}
toString() {
if (this.count === 0) {
return ''
}
// 类似于数组的join方法
let str = `${this.head.element}`;
let current = this.head.next;
for (let i = 1; i < this.count && current !== undefined; i++) {
str = `${str}, ${current.element}`;
current = current.next;
}
return str;
}
// 添加元素
push(element) {
const node = new Node(element);
let current;
if (this.head === undefined) {
this.head = node;
} else {
current = this.head;
while (current.next !== undefined) {
current = current.next;
}
// 将其 next 赋为新元素,建立链接
current.next = node;
}
this.count++;
}
// 通过序号获取元素
getElementAt(index) {
// 是否是多余的判断
if (index >= 0 && index < this.count) {
let node = this.head;
for (let i = 0; i < index && node !== undefined; i++) {
node = node.next;
}
return node;
}
return undefined;
}
// 按序号移除元素
removeAt(index) {
// 检查越界值
if (index >= 0 && index < this.count) {
let current = this.head;
// 移除第一项
if (index === 0) {
this.head = current.next;
} else {
const prevNode = this.getElementAt(index - 1);
current = prevNode.next;
// 将prevNode与current的下一项链接起来:跳过current,从而移除它
prevNode.next = current.next;
}
this.count--;
return current.element;
}
return undefined;
}
// 返回一个元素的位置
indexOf(element) {
let current = this.head;
for (let i = 0; i < this.count && current !== undefined; i++) {
if (this.equalsFn(current.element, element)) {
return i;
}
current = current.next;
}
return -1;
}
// 移除元素
remove(element) {
const index = this.indexOf(element);
return this.removeAt(index);
}
// 在任意位置插入元素
insert(element, index) {
if (index >= 0 && index <= this.count) {
const node = new Node(element);
if (index === 0) {
const current = this.head;
node.next = current;
this.head = node;
} else {
const prevNode = this.getElementAt(index - 1);
const current = prevNode.next;
prevNode.next = node;
node.next = current;
}
this.count++;
return true;
}
return false;
}
}
const link = new LinkedList()
console.log('长度', link.size())
console.log('是否为空', link.isEmpty())
link.push('ross')
link.push('jack')
link.push('roma')
console.log('长度', link.size())
console.log('是否为空', link.isEmpty())
console.log('删除第一个元素', link.removeAt(0))
console.log('长度', link.size())
console.log('在节点2插入一个元素', link.insert('new', 2))
console.log(link.toString())
console.log('获取roma位置', link.indexOf('roma'))
console.log('删除', link.remove('roma'))
console.log('长度', link.size())
console.log(link.toString())
console