1侠鳄、鏈表的優(yōu)缺點(diǎn)
優(yōu)點(diǎn):
- 插入刪除速度快
- 內(nèi)存利用率高埠啃,不會(huì)浪費(fèi)內(nèi)存
- 大小沒有固定,拓展很靈活伟恶。
缺點(diǎn):
- 不能隨機(jī)查找碴开,必須從第一個(gè)開始遍歷,查找效率低
2尝偎、 鏈表的JS實(shí)現(xiàn)
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
}
append(element) {
let node = new Node(element);
if (!this.head) {
this.head = node;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
this.length++;
return true;
}
insert(position, element) {
let node = new Node(element);
if (position < 0 || position > this.length) {
return false;
}
let current = this.head;
let previous;
let index = 0;
if (position === 0) {
node.next = current;
this.head = node;
} else {
while (index < position) {
previous = current;
current = current.next;
index++;
}
previous.next = node;
node.next = current;
}
this.length++;
return true;
}
update(position, element) {
if (position < 0 || position >= this.length) {
return false;
}
let index = 0;
let current = this.head;
while (index < position) {
current = current.next;
index++;
}
current.data = element;
return true;
}
indexOf(element) {
let index = 0;
let current = this.head;
while (current) {
if (current.data === element) {
return index;
}
current = current.next;
index++;
}
return -1;
}
removeAt(position) {
if (position < 0 || position >= this.length) {
return null;
}
let current = this.head;
if (position === 0) {
this.head = current.next;
} else {
let index = 0;
let previous;
while (index < position) {
previous = current;
current = current.next;
index++;
}
previous.next = current.next;
}
this.length--;
return current.data;
}
remove(element) {
const position = this.indexOf(element);
return this.removeAt(position);
}
isEmpty() {
return this.length === 0;
}
size() {
return this.length;
}
toString() {
let current = this.head;
let restult = '';
while (current) {
restult += current.data + (current.next ? ' > ' : ' ');
current = current.next;
}
return restult;
}
}