链表:单向链表,双向链表,循环链表,双向循环链表
链表是分散于硬盘的存储空间,和数组不一样,数组是一个连续的存储空间,而且链表和数组相比无序,且不连续。但是他们都是线性表。在有序和无序的情况下,他们的时间复杂度会随着变化而变化
无序 链表查找的速度比数组慢,复杂度都为O(n),但是数组要比链表稍微快一点,因为数组是连续的存储空间。链表的插入速度和数组差不多快,时间复杂度都是o(1)。在删除的时候,链表的时间复杂度比数组慢,虽然他们的时间复杂度都是O(n),但是数组是连续存储
有序 链表的查找速度和数组的查找速度时间复杂度都是O(n), 链表可以通过跳表来进行优化,数组可以通过二分法来进行优化,删除时间复杂度也是同样是O(n),添加的时候链表为O(n) ,数组的时间复杂度为O(n+m)
以下是实现单向链表
//封装结点对象
class Node {
constructor(element) {
this.element = element;
this.next = null;
}
}
length = 0;
head = null; //public
class LinkedList {
constructor() {}
//向链表末尾追加元素
append(element) {
let node = new Node(element);
console.info("node的值", node);
let current = null; //当前位置的
if (head === null) {
head = node;
} else {
current = head;
while (current.next) {
current = current.next; //找到null
}
current.next = node;
}
this.length++;
}
//删除特定地方的元素
removeEle(position) {
//值在区间内
if (position > -1 && position < this.length) {
let current = head;
let previous,
index = 0;
if (position === 0) {
//直接移除第一项
this.head = curren.next;
} else {
while (index++ < position) {
previous = current;
previous.next = current.next;
}
previous.next = current.next;
}
this.length--;
return current.element;
} else {
return null;
}
}
//在任意位置插入一个元素
insert(element, position) {
if (position > 0 && position < this.length) {
let node = new Node(element),
current = head,
previous,
index = 0;
if (position === 0) {
// 在第一个位置添加
node.next = current;
head = node;
} else {
while (index++ < position) {
previous = current;
current = current.next;
}
node.next = current; // 在previous与current的下一项之间插入node
previous.next = node;
}
length++;
return true;
} else {
this.length++;
return true;
}
}
// 把链表内的值转换成一个字符串
toString() {
let current = head,
string = "";
while (current) {
string += current.element + " ";
current = current.next;
}
return string;
}
// 在链表中查找元素并返回索引值
indexOf(element) {
let current = head,
index = 0;
while (current) {
if (element === current.element) {
return index;
}
index++;
current = current.next;
}
return -1;
}
// 从链表中移除指定元素
remove(element) {
let index = this.indexOf(element);
return this.removeAt(index);
}
isEmpty() {
return length === 0;
}
size() {
return length;
}
getHead() {
return head;
}
}
let list = new LinkedList();
list.append(1);
list.append(2);
// console.log(list.toString()); // 1 2
list.insert(0, "hello");
list.insert(1, "world");
console.log(list.toString());
// console.log(list.toString()); // hello world 1 2
// list.remove(1);
// list.remove(2);
// console.log(list.toString()); // hello world
网友评论