双向链表
- 对于栈与队列,利用js数组的可拓展性可以非常方便的实现
- 而对于链表,开始可能并不非常习惯,我个人是使用了画图的方式。把一个链表画出来,把要实现的方法画出来,对着图实现代码,非常的圆滑和舒服,很Nice!
- 数据结构之美越来越被发掘,毕竟js数组的弊端就摆在那里。上代码吧
'use strict'
class listNode {
constructor(element) {
this.previous = null;
this.element = element;
this.next = null
}
}
class doublyaLinkedList {
// 构造函数
constructor() {
this.head = null;
this.length = 0;
this.tail = null;
}
// 尾部插入节点 (√)
append(element) {
let node = new listNode(element)
let current = this.head
if (!this.head) {
this.head = node
} else {
while (current.next) {
current = current.next
}
current.next = node
node.previous = current
}
this.length++
}
// 插入节点(√)
insert(position, element) {
let node = new listNode(element)
let index = 1
let current = this.head
let previous = this.head
if (position <= 0 || position > this.length) {
return 'ERROR'
} else if (position == 1) {
this.head = node
node.next = current
current.previous = node
} else {
while (index++ < position) {
current = current.next
}
current.previous.next = node
node.next = current
node.previous = current.previous
current.previous = node
}
this.length++
}
// 根据节点序号删除(√)
removeAt(position) {
let index = 1
let current = this.head
if (position <= 0 || position > this.length) {
return 'ERROR'
} else {
if (position == 1) {
this.head = current.next
} else {
while (index++ < position) {
current = current.next
}
current.previous.next = (position == this.length) ? null : current.next
if (position != this.length) {
current.next.previous = current.previous
}
current.previous = null;
}
}
this.length--;
}
// 查询节点位置,无则返回-1(√)
indexOf(element) {
let current = this.head
let index = 1
while (index ++ <= this.length) {
if (current.element === element) {
return index - 1
}
current = current.next
}
return -1
}
// 根据节点内容删除(√)
remove(element) {
this.removeAt(this.indexOf(element));
}
// 查询大小
size() {
return this.length
}
// 仅作测试用
showAll() {
let index = 1
let current = this.head
console.log('==== 显示所有节点内容 ====');
while (index++ < this.length) {
console.log(current.element)
current = current.next
}
console.log(current.element)
console.log('===== 显示结束 =====')
}
}
// 测试
let list = new doublyaLinkedList()
console.log('1. 测试append()');
for (let i = 1; i <= 5; i++) {
list.append(i)
}
list.showAll()
console.log('======================');
console.log('2. 测试insert()');
list.insert(3,9999)
list.showAll()
console.log('======================');
console.log('3. 测试removeAt()');
list.removeAt(3)
list.showAll()
console.log('======================');
console.log('4. 测试indexOf()');
console.log(list.indexOf(2));
console.log('======================');
console.log('5. 测试remove()');
list.remove(3)
list.showAll()
console.log('======================');
console.log('6. 测试size()');
console.log(list.size());
console.log('======================');