基本的数据结构 - 链表
链表的概念特点
- 有序集合;
- 内存空间不是连续;
- 在创建的时候可以先不必确定大小,并且大小是可以无限扩展的;
- 每一个元素由一个存储元素本身的节点和一个指向下一个元素的引用(指针或链接)组成。
- 插入或删除元素时间复杂度可以达到O(1),效率较高;
- 查找元素的时候需要从头开始查找,无法跳过第一个元素访问任何元素;
- 同样无法通过下标直接访问元素,需要从头开始。
链表常用的方法
- enQueue(element): 添加新元素到队列尾部
- deQueue(): 删除队列的第一项元素,并将其返回
- peek(): 只查看队列的第一项元素
- isEmpty(): 判空,队列为空返回true,反之false
- clear(): 清空队列
- size(): 返回队列的大小
- toString(): toString方法
链表的实现
function LinkedList() {
function Node(data) {
this.data = data;
this.next = null;
}
this.head = null;
this.length = 0;
LinkedList.prototype.append = function (data) {
const nweNode = new Node(data);
if (this.length === 0) {
this.head = nweNode;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = nweNode;
}
this.length += 1;
};
LinkedList.prototype.toString = function () {
let current = this.head;
let listStr = "";
while (current) {
listStr += current.data + " ";
current = current.next;
}
return listStr;
};
LinkedList.prototype.insert = function (position, data) {
if (position < 0 || position > this.length) {
return false;
}
const newData = new Node(data);
if (position === 0) {
newData.next = this.head;
this.head = newData;
} else {
let index = 0;
let current = this.head;
let previous = null;
while (index++ < position) {
previous = current;
current = current.next;
}
previous.next = newData;
newData.next = current;
}
this.length += 1;
return true;
};
LinkedList.prototype.get = function (position) {
if (position < 0 || position > this.length) {
return false;
}
let current = this.head;
let index = 0;
while (index++ < position) {
current = current.next;
}
return current.data;
};
LinkedList.prototype.indexOf = function(data){
let current = this.head;
let index = 0;
while(current){
if(current.data === data){
return index;
}
current = current.next;
index += 1;
}
return -1;
}
LinkedList.prototype.update = function (position, newData) {
if (position < 0 || position >= this.length) {
return false;
}
let current = this.head;
let index = 0;
while (index++ < position) {
current = current.next;
}
current.data = newData;
return true;
};
LinkedList.prototype.removeAt = function (position) {
if (position < 0 || position >= this.length) {
return false;
}
let current = this.head;
if (position === 0) {
this.head = null;
} else {
let index = 0;
let previous = null;
while (index++ < position) {
previous = current;
current = current.next;
}
previous.next = current.next;
}
this.length -= 1;
return current.data;
};
LinkedList.prototype.remove = function (data) {
let position = this.indexOf(data);
return this.removeAt(position);
};
LinkedList.prototype.isEmpty = function () {
return this.length === 0;
};
LinkedList.prototype.size = function () {
return this.length;
};
}