代码:
function LinkedList() {
// 定义一个结点,链表就是由一个个的结点连接起来的
let Node = function (element) {
this.element = element;
this.next = null;
};
// 定义链表头指针
let head = null;
// 定义一个变量来记录链表长度
let length = 0;
// 下面开始定义方法
//一、 向列表尾添加一个新的项
this.append = function (element) {
// 建立一个存放新插入的数据的结点,current为一个结点变量。
let node = new Node(element),
current;
// 如果没有结点,也就是头指针为空,那么我们就让我们插入的结点成为头结点
if (head === null) {
head = node;
} else {
current = head;
// 如果头结点不为空,那么就一直循环,直到找到最后一个结点
while (current.next !== null) {
current = current.next;
}
// 让最后一个结点等于我们插入的结点
current.next = node;
}
// 链表长度加一
length++;
};
//二、 根据位置从链表中移除一项,从0开始排序
this.removeAt = function (position) {
// 检测位置是否越界
if (position > -1 && position < length) {
// 把current当作head的副本
let current = head,
previous,
index = 0;
// 删除的位置是头结点
if (position === 0) {
head = current.next;
} else {
// 找到要删除的结点的位置
while (index++ < position) {
previous = current;
current = current.next;
}
// 跳过current结点,也就是对其进行删除
previous.next = current.next;
}
length--;
// 返回删除的元素
return current.element;
} else {
return null;
}
};
// 三、在任意位置插入元素,第一个形参为插入位置,第二个为要插入的元素
this.insert = function (position, element) {
// 检查插入的位置是否合理
if (position >= 0 && position <= length) {
let node = new Node(element),
current = head,
previous,
index;
// 在最开始插入
if (position === 0) {
node.next = current;
head = node;
} else {
// 在其他位置插入,先找到要插入的位置
while (index++ < position) {
previous = current;
current = current.next;
}
// 进行插入
node.next = current;
previous.next = node;
}
length++;
return true;
} else {
return false;
}
};
// 四、将LinkList对象转换成一个字符串
this.toString = function () {
let current = head,
string = "";
while (current) {
// 拼接字符串
string += current.element + " ";
current = current.next;
}
return string;
};
//五、 找元素,找到就返回该元素的位置,找不到返回-1
this.indexOf = function (element) {
let current = head,
index = 0;
while (current) {
if (element === current.element) {
return index;
}
index++;
current = current.next;
}
return -1;
};
// 六、移除一个任意元素
this.remove = function (element) {
let index = this.indexOf(element);
return this.removeAt(index);
};
// 七、判断链表是否为空
this.isEmpty = function () {
return length === 0;
};
// 八、返回数组中元素个数
this.size = function () {
return length;
};
// 九、返回第一个元素
this.getHead = function () {
return head;
};
}
实现:
let linkList = new LinkedList();
console.log(linkList.isEmpty()) // true
linkList.append(1);
linkList.append(2);
linkList.append(3);
linkList.append(4);
linkList.append(5);
console.log(linkList.isEmpty()) // false
console.log(linkList.size()) // 5
console.log(linkList.getHead()) // Node {element: 1, next: Node}
console.log(linkList.toString()); // 1 2 3 4 5
console.log(linkList.indexOf(1)) // 0
linkList.insert(0,666)
linkList.removeAt(5)
linkList.removeAt(4)
console.log(linkList.toString()) // 666 1 2 3