一、链表(LinkedList)
数据结构的逻辑结构分为:集合结构、线性结构、树形结构、图形结构
物理结构分为:顺序存储结构、链接存储结构
顺序存储结构表现为:数组
链接存储结构表现为:链表
单链表
双向链表
单向循环链表
二、使用JS实现链表
1. 单链表
实现单链表的原理在于,要不断更新节点的next指针,使整个链表串联起来
class Node {
constructor(val) {
this.value = val
this.next = null
}
}
class LinkedList {
constructor(val) {
//初始化链表长度
this.length = 0
//初始化链表第一个节点
this.head = null
}
//增加节点
append(val) {
let newAppendNode = new Node(val) //创建一个新节点
let p //指针
if (this.head === null) {
this.head = newNode //如果链表没有头节点,就把这个新增的节点作为头节点
} else {
//如果存在头节点
p = this.head
while (p.next) {
//遍历到单链表尾部
p = p.next //p最终指向尾节点
}
p.next = newAppendNode //在尾节点后添加节点
}
this.length++ //别忘了更新链表长度
}
//插入元素,成功true,失败false
insert(position, val) {
let newInsertNode = new Node(val)
if (position >= 0 && position < this.length) {
let current = this.head
let previous = null
let index = 0
if (position == 0) {
newInsertNode.next = current
this.head = newInsertNode
} else {
while (index < position) {
previous = current
current = current.next
index++
}
newInsertNode.next = current
previous.next = newInsertNode
}
this.length++ //别忘了更新链表长度
return true
} else {
return false
}
}
//根据位置删除指定节点,成功返回元素,失败返回null
removeAt(position) {
if (position >= 0 && position < this.length) {
var current = this.head //current指针用来指向该指定节点
var previous = null //previous指针指向current指针前一个节点
var index = 0 //纪录是否到达指定位置
if (position == 0) {
this.head == current.next
} else {
while (index < position) {
previous = current //每次将previous指针和current指针向后移动一个,直到到达指定节点
current = current.next
index++
}
previous.next = current.next //该指定节点的前一个指针越过指定节点,直接指向其下一个节点
}
this.length-- //别忘了更新链表长度
return current.val //返回该元素
} else {
return null
}
}
//根据元素删除指定元素,成功返回已删除的节点,失败返回null
remove(val) {
let index = this.find(val)
return this.removeAt(index)
}
//根据元素查找节点,成功返回给定元素的索引,如果没有则返回-1
find(val) {
var current = this.head
var index = 0
if (current.val == val) {
return 0
}
while (current) {
if (current.val == val) {
return index
}
current = current.next
index++
}
return -1
}
isEmpty() {
return this.length == 0
}
size() {
return this.length
}
toString() {
let str = ''
let current = this.head
while (current) {
str += ',' + current.val
current = current.next
}
return str
}
}
// 创建链表
var li = new LinkedList()
li.append(1)
li.append(2)
li.append(4)
li.append(4)
li.append(5)
li.insert(2, 3)
li.insert(2, 3)
console.log(li.toString()) // 1,2,3,3,4,4,5