链表常见操作
我们先来认识一下, 链表中应该有哪些常见的操作
append(element)
:向列表尾部添加一个新的项insert(position, element)
:向列表的特定位置插入一个新的项。remove(element)
:从列表中移除一项。indexOf(element)
:返回元素在列表中的索引。如果列表中没有该元素则返回-1
。removeAt(position)
:从列表的特定位置移除一项。isEmpty()
:如果链表中不包含任何元素,返回true
,如果链表长度大于0则返回false
。size()
:返回链表包含的元素个数。与数组的length
属性类似。toString()
:由于列表项使用了Node
类,就需要重写继承自JavaScript对象默认的toString
方法,让其只输出元素的值。
<script>
//创建节点,有data和next属性
class Lnode {
constructor(data) {
this.data = data;
this.next = null
}
}
//链表
class LinkeList {
constructor() {
this.head = null;
this.length = 0;
}
//添加
append(el) {
let newnode = new Lnode(el);
if (this.head == null) {
this.head = newnode;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newnode
}
this.length++;
}
//插入
insert(position<