开始手写代码
1 手写JS单链表
- 请自行在一个新的js文件中测试
class Node {
constructor(data) {
this.data = data
this.next = null
}
}
class LinkedList {
constructor() {
this.head = null
this.tail = null
this.length = 0
}
isEmpty () {
return this.length === 0
}
push (data) {
const node = new Node(data)
if (this.head == null) {
this.head = node
this.tail = node
}
this.tail.next = node
this.tail = node
this.length++
}
pop () {
if (this.isEmpty()) {
return null
}
if (this.head == this.tail) {
this.head = null
this.tail = null
this.length--
return this.tail
}
let node = this.tail
let currentNode = this.head
let penultimate
while (currentNode) {
if (currentNode.next === this.tail) {
penultimate = currentNode
break
}
currentNode = currentNode.next
}
penultimate.next = null
this.tail = penultimate
this.length--
return node //返回尾节点
}
print () {
const list = []
let currentNode = this.head
while (currentNode) {
list.push(currentNode.data)
currentNode = currentNode.next
}
return list.join("=>")
}
get (index) {
if (index == 0) {
return this.head
}
if (index < 0 || index >= this.length) {
return null
}
let currentNode = this.head
let i = 0
while (i < index) {
i++
currentNode = currentNode.next
}
return currentNode
}
delete (index) {
let currentNode = this.head
if (index == 0) {
this.length--
let deletedNode = currentNode
this.head = this.head.next
return deletedNode //返回被删除的节点
}
if (index < 0 || index >= this.length) {
return null;
}
let i = 0
let previous
while (i < index) {
i++
previous = currentNode
currentNode = currentNode.next
}
previous.next = currentNode.next
this.length--
return currentNode //返回被删除的节点
}
}
const l = new LinkedList();
const values = ["A", "B", "C", "D", "E"];
values.forEach(value => l.push(value));
console.log(l);
console.log(l.print());
console.log(l.pop());
console.log(l.print());
console.log(l.get(2));
console.log(l.isEmpty());
console.log(l.delete(2));
console.log(l.print());
- 以下是控制台输出
//以下是控制台输出
LinkedList {
head: Node { data: 'A', next: Node { data: 'B', next: [Node] } },
tail: Node { data: 'E', next: null },
length: 5
}
A=>B=>C=>D=>E
Node { data: 'E', next: null }
A=>B=>C=>D
Node { data: 'C', next: Node { data: 'D', next: null } }
false
Node { data: 'C', next: Node { data: 'D', next: null } }
A=>B=>D
2 总结
- 单链表的基本操作有pop push isEmpty print delete get等
- 需定义Node类再定义LinkedList类