最近复习数据结构,使用 ES6 语法实现了链表,若有更好的方法,希望大佬们指点指点,谢谢~ ?
实现的操作链表函数:
- append 在链表尾部添加一个新的项
- insert 向列表的特定位置插入一个新的项
- removeAt 从列表特定位置移除一项
- remove 从列表中移除一项
- indexOf 返回元素在列表中的索引
- isEmpty 是否是为空链表
- size 返回链表包含的元素个数
- getHead 返回表头
- toString 输出元素的值
代码
//节点
class Node{
constructor(element){
this.element = element;//节点内容
this.next = null;
}
}
//链表
class LinkedList{
/**
* 传入数组创建链表
* @param {*} array
*/
constructor(array){
this.length = 0;//链表长度
this.head = null;//链表头
if(array.length != 0){
this.head = new Node(array.shift());
let current = this.head;
array.forEach(element => {
let node = new Node(element);
current.next = node;
current = node;
});
this.length = array.length + 1;
}
}
/**
*