小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
何为链表?
链表存储的数据是有序的,但不同于数组,链表中的元素不是连续放置的,每一个元素由一个存储元素本身的节点和一个指向下一个元素的引用(也称指针或者链接)组成
链表的好处在于,添加或者移除元素的时候,不需要移动其他元素,但是当我们想要访问链表中间的一个元素,我们需要从起点(表头)开始送达,直到找到我们需要的元素
创建链表
function LinkedList() {
function Node(data) {
this.data = data
this.next = null
}
//属性
this.head = null
this.length = 0
}
创建添加方法
//追加方法
LinkedList.prototype.append = function (data) {
//1创建新节点
var newNode = new Node(data)
//2.判断是否是第一个节点
if (this.length == 0) {
this.head = newNode
} else {
//找到最后一个节点
var current = this.head
while (current.next) {
current = current.next
}
//最后节点的next指向新的节点
current.next = newNode
}
//链表长度加一
this.length += 1
}
重写tostring方法
//2.tostring方法
LinkedList.prototype.toString = function () {
var current = this.head
var listString = ""
while (current) {
listString += current.data + " "
current = current.next
}
return listString
}
在特定的位置插入元素
//insert方法
LinkedList.prototype.insert = function (position, data) {
//判断是否越界
if (position < 0 || position > this.length) return false
var newNode = new Node(data)
if (position == 0) {
newNode.next = this.head
this.head = newNode
} else {
var index = 0
var current = this.head
var previous = null
while (index++ < position) {
previous = current
current = current.next
}
newNode.next = current
previous.next = newNode
}
}
删除元素removeAt方法
LinkedList.prototype.removeAt = function (position) {
if (position < 0 || position >= this.length) return null
// 定义变量
var index = 0
var current = this.head
var previous = null
if (position == 0) {
this.head = current.next
} else {
while (index++ < position) {
previous = current
current = current.next
}
previous.next = current.next
}
this.length -= 1
return current.data
}
查看链表长度indexOf方法
LinkedList.prototype.indexOf = function (position) {
var index = 0
var current = this.head
while (current) {
if (current.data == position) {
return index
}
index++
current = current.next
}
return -1
}
根据元素删除链表
LinkedList.prototype.remove = function (position) {
var index = this.indexOf(position)
return this.removeAt(index)
}