-
Notifications
You must be signed in to change notification settings - Fork 0
/
doublyLinkedNode.js
40 lines (37 loc) · 1 KB
/
doublyLinkedNode.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// https://humanwhocodes.com/blog/2019/02/computer-science-in-javascript-doubly-linked-lists/
// https://github.com/humanwhocodes/computer-science-in-javascript/tree/master/src/data-structures/doubly-linked-list
// !!! 双向链表节点
class doublyLinkedListNode {
constructor(data) {
this.data = data;
this.previous = null;
this.next = null;
}
}
// 创建首节点
let head = new doublyLinkedListNode(12);
// 创建第二节点
let secondNode = new doublyLinkedListNode(99);
head.next = secondNode;
secondNode.previous = head;
// 创建第三节点
let thirdNode = new doublyLinkedListNode(37);
secondNode.next = thirdNode;
thirdNode.previous = secondNode;
let tail = thirdNode;
// 打印链表
console.log(head);
// 正向遍历
let current = head;
while (current !== null) {
console.log(current.data);
current = current.next;
}
// 12 99 37
// 反向遍历
let reverse = tail;
while (reverse !== null) {
console.log(reverse.data);
reverse = reverse.previous;
}
// 37 99 12