1.单链表

- 链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。
- 特点:插入的时间复杂度O(1),比线性表快得多,但是查找需要O(n),而线性表和顺序表相应的时间而线性表和顺序表相应的时间复杂度分别是O(logn)和O(1)。
class Node {
constructor(element) {
this.element = element;
this.next = null
}
}
class LinkList {
constructor() {
this.head = null;
this.length = 0;
}
append(element) {
const node = new Node(element)
let current = null;
if(this.head === null) {
this.head = node
}else {
current = this.head;
while(current.next) {
current = current.next
}
current.next = node;
}
this.length++
}
indexOf(elemet) {
let index = -1;
let current = this.head;
while(current.next) {
if(elemet === current.element) {
return index + 1
}
index++;
current = current.next
}
return -1
}
getElementAt(position) {
if(position < 0 || position >= this.length) {
return null
}
let current = this.head
for(let i = 0; i < position; i++) {
current = current.next
}
return current;
}
insert(position, element) {
const node = new Node(element);
if(position < 0 || position > this.length) {
return null;
}
if (position === 0) {
node.next = this.head;
this.head = node
} else {
let previous = this.getElementAt(position - 1);
node.next = previous.next;
previous.next = node;
}
this.length++
}
removeAt(position) {
if(position < 0 || position > this.length) {
return null
}
let current = this.head
if(position === 0) {
this.head = current.next;
}else {
let previous = this.getElementAt(position - 1)
current = previous.next;
previous.next = current.next;
}
this.length--
}
remove(element) {
const position = this.indexOf(element)
this.removeAt(position);
}
}
let list = new LinkList()
list.append('name')
list.append('age')
list.append('leng')
list.append('last')
console.log(list);
list.insert(2, 'man')
console.log(list)
list.removeAt(2)
list.remove('age')
console.log(list)