//通过链表 实现 key-value 类型结构
let NodeMap = function (key, value) {
this.key = key;
this.value = value;
this.next = null;
}
class MapList {
//构造函数
constructor() {
this.length = 0;
this.head = null;
}
//向链表中添加节点,默认添加在链表尾部
append = function (key, value) {
let node = new NodeMap(key, value);
if (this.head == null) this.head = node;
else {
let cur = this.getElementAt(this.length - 1);
cur.next = node;
}
this.length++;
}
//向链表中positon位置处添加节点value
insert = function (position, key, value) {
if (position < 0 || position > this.length) return false;
let node = new NodeMap(key, value);
if (position == 0) {
node.next = this.head;
this.head = node;
}
else {
let previous = this.getElementAt(position - 1);
if (previous) {
node.next = previous.next;
previous.next = node;
}
}
this.length++;
return true;
}
//取出链表索引所在对应的元素
getElementAt = function (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;
}
//删除链表中对应的元素
removeAt = function (position) {
//移除位置超出链表范围
if (position < 0 || position >= this.length) return false;
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--;
return current.element;
}
//移除指定的节点
removeNode = function (key) {
let index = this.indexOf(key);
return this.removeAt(index);
}
//在;链表中查找给定元素的索引
indexOf = function (key) {
let current = this.head;
for (let i = 0; i < this.length; i++) {
if (current.key == key) return i;
current = current.next;
}
return -1;
}
//判断链表是否为空
isEmpty = function () {
return this.length === 0;
}
//获取链表长度
size = function () {
return this.length;
}
//返回链表的头元素
getHead = function () {
return this.head;
}
//清空链表
clear = function () {
this.head = null;
this.length = 0;
}
//按指定格式,输出链表中元素
toString = function () {
let current = this.head;
let s = '';
while (current) {
let next = current.next;
next = next ? next.value : 'null';
let key = current.key;
key = key ? key : 'null';
s += `[element:${current.value},next:${next},key:${key}]`;
current = current.next;
}
return s;
}
}