一、单向链表的优点
进行数据的删除、插入简单;
二、单向链表的缺点
进行数据查找时比较慢;
三、使用类进行封装
class Node {
constructor(element) {
this.element = element;
this.next = null;
}
}
class LinkList {
constructor() {
this.count = 0;
this.head = null;
}
push(data) {
const node = new Node(data);
if (this.head === null) {
this.head = node;
} else {
let current = this.head;
while (current.next !== null) {
current = current.next;
}
current.next = node;
}
this.count++;
}
removeAt(index) {
if (index >= 0 && index < this.count) {
let current = this.head;
if (index == 0) {
this.head = this.head.next;
} else {
let previous;
for (let i = 0; i < index; i++) {
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.count--;
return current.element;
}
return false
}
removeAt2(index) {
if (index >= 0 && index < this.count) {
let current = this.head;
if (index == 0) {
this.head = this.head.next;
} else {
let previous = this.getNodeAt(index - 1);
current = previous.next;
previous.next = current.next;
}
this.count--;
return current.element;
}
}
equal(a, b) {
// return a=== b;
return JSON.stringify(a) === JSON.stringify(b);
// imumutable 判断数据相等的插件库
}
indexOf(element) {
let current = this.head;
for (let i = 0; i < this.count; i++) {
if (current.element == element) {
return i;
}
current = current.next;
}
}
remove(element) {
const index = this.indexOf(element);
this.removeAt(index);
}
getNodeAt(index) {
if (index >= 0 && index < this.count) {
let node = this.head;
for (let i = 0; i < index; i++) {
node = node.next;
}
return node;
}
return false
}
insert(element, index) {
if (0 <= index || index <= this.count) {
let node = new Node(element);
if (index == 0) {
let current = this.head;
node.next = current;
this.head = node;
} else {
let previous = this.getNodeAt(index - 1);
let next = previous.next;
node.next = next;
previous.next = node;
}
this.count++;
return true;
}
return false;
}
size() {
return this.count;
}
isEmpty() {
return this.size() === 0;
}
getHead() {
return this.head;
}
}