Node.js自定义链表
链表(Linked list)是一种常见的基础数据结构,是一种线性表,但是不像顺序表一样连续存储数据,而是每一个结点(数据存储单元)里存放下一个结点的信息(即地址)
方法介绍:
. is_empty():链表是否为空
. length():链表长度
. travel():遍历整个链表
. add(item):链表头部添加元素
. append(item):链表尾部添加元素
. insert(pos, item):指定位置添加元素
. remove(item):删除节点
. search(item):查找节点是否存在
. reverse(): 链表倒置
代码:
class Node {
// 节点
constructor(item) {
this.item = item
this.next = null
}
}
class Link {
// 链表
constructor() {
this._head = null
}
add(item) {
// 添加元素
let node = new Node(item)
node.next = this._head
this._head = node
}
travel() {
// 遍历
let cur = this._head
while (cur) {
console.log(cur.item)
cur = cur.next
}
}
isEmpty() {
return this._head === null
}
length() {
// 长度
let count = 0
let cur = this._head
while (cur) {
count += 1
cur = cur.next
}
return count
}
append(item) {
// 向链尾添加元素
let node = new Node(item)
if (this._head === null) {
this._head = node
return
}
let pre = null
let cur = this._head
while (cur) {
pre = cur
cur = cur.next
}
// 当while循环结束的时候,pre就指向了链表中最后一个节点
pre.next = node
}
insert(pos, item) {
// 将item对应的节点插入到pos指定的位置中
let node = new Node(item)
if (pos === 0) {
node.next = this._head
this._head = node
return
}
let cur = this._head
let pre = null
for (let i = 0; i < pos; i++) {
pre = cur
cur = cur.next
}
pre.next = node
node.next = cur
}
remove(item) {
// 删除节点
if (this._head && this._head.item === item) {
this._head = this._head.next
return
}
let cur = this._head
let pre = null
while (cur) {
pre = cur
cur = cur.next
if (cur.item === item) {
pre.next = cur.next
return;
}
}
}
search(item) {
// 查询某个节点是否存在
let cur = this._head
while (cur) {
if (cur.item === item) {
return true
}
cur = cur.next
}
return false
}
reverse() {
// 链表倒置
let pre = this._head
let cur = pre.next
let next_node = cur.next
pre.next = null // 链表倒置后pre就是最后一个节点,最后一个节点的next指向None
while (1) {
cur.next = pre
pre = cur
cur = next_node
if (next_node !== null) {
next_node = next_node.next
} else {
break
}
}
this._head = pre
}
}
link = new Link()
link.add(1)
link.add(2)
link.add(3)
link.add(4)
link.add(5)
link.insert(0, 0)
link.remove(0)
link.reverse()
link.travel()
console.log(link.isEmpty())
console.log(link.length())