目录
个人博客地址:https://tao-yuhan.gitee.io/tyhanblog/
链表的优势
- 链表中的元素在内存中不必是连续的空间
- 链表的每一个元素由一个存储元素本身的节点和一个指向下一个元素的引用
- 链表在创建的时候不需要确定大小,大小可以无线延伸下去
单向链表的一些基本操作
链表得有一个head指向第一个节点,其次每个节点中有data和next,next指向下一个节点
- append(element): 在尾部添加一个新的项
- insert(position,ele): 向链表的特定位置插入一个新的项
- get(position): 获取对应位置的元素
- indexOf(ele): 返回元素在链表中的索引,如果没有该元素则返回-1
- update(position,ele): 修改某个位置的元素
- removeAt(position): 从列表的特定位置移除一项
- remove(ele): 从链表中移除一项
- isEmpty(): 是否为空
- size(): 链表长度
- toString(): 输出元素的值
链表操作的封装
链表的基本实现
function LinkedList() {
this.head = null
this.length = 0
//节点类
function Node(data) {
this.data = data
this.next = null
}
}
1.append
LinkedList.prototype.append = function (data) {
//先创建这个节点
let newNode = new Node(data)
//如果添加的为第一个节点,将head指针指向该节点的data
if (this.length == 0) {
this.head = newNode
} else {
let current = this.head
while (current.next) {
//找下一个
current = current.next
}
//最后节点的next指向新的节点
current.next = newNode
}
this.length++
}
2.insert
LinkedList.prototype.insert = function (position, data) {
//对position进行越界判断和长度判断
if (position < 0 || position > this.length) return false
//创建节点
let newNode = new Node(data)
//如果是插入在第一个
if (position == 0) {
newNode.next = this.head
this.head = newNode
} else {
//如果不是插入第一个
let index = 0 //自己定义一个位置
let current = this.head //先让current为第一个节点
while (index++ < position - 1) {
//3
current = current.next
}
newNode.next = current.next
current.next = newNode
}
this.length++
return true
}
3.get
LinkedList.prototype.get = function (position