-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList.js
149 lines (133 loc) · 2.95 KB
/
LinkedList.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
// 单链表
import LinkedListNode from './LinkedListNode.js';
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
}
// 添加新节点
append(element) {
const newNode = new LinkedListNode(element);
if (!this.head) {
this.head = newNode;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = newNode;
}
this.length++;
return this;
}
// 插入节点
insert(position, element) {
if (position < 0 || position > this.length) {
console.error('insert position 超出边界');
return this;
}
const newNode = new LinkedListNode(element);
if (position === 0) {
newNode.next = this.head;
this.head = newNode;
} else {
let idx = 0;
let prev;
let current = this.head;
while (idx++ < position) { // 移动指针到 position
prev = current;
current = current.next;
}
newNode.next = current;
prev.next = newNode;
}
this.length++;
return this;
}
// 删除指定位置的节点
removeAt(position) {
if (position < 0 || position >= this.length) {
console.error('removeAt position 超出边界');
return this;
}
if (position === 0) {
this.head = this.head.next;
} else {
let idx = 0;
let prev;
let current = this.head;
while (idx++ < position) { // 移动指针到 position
prev = current;
current = current.next;
}
prev.next = current.next;
}
this.length--;
return this;
}
// 删除指定值
remove(element) {
if (this.head.value === element) {
this.head = this.head.next;
this.length--;
return this;
}
let idx = 0;
let prev;
let current = this.head;
while (idx < this.length && current.value !== element) {
prev = current;
current = current.next;
idx++;
}
if (idx >= this.length) { // 没找到该元素
console.error('未找到该元素');
prev.next = null;
return this;
}
prev.next = current.next;
this.length--;
return this;
}
// 获取下标,未找到返回 -1
indexOf(element) {
let idx = 0;
let current = this.head;
while (idx < this.length && current.value !== element) {
current = current.next;
idx++;
}
if (idx >= this.length) { // 没找到该元素
return -1;
}
return idx;
}
// 是否为空链表
isEmpty() {
return this.head === null;
}
size() {
return this.length;
}
// 获取head
getHead() {
if (this.head) {
return this.head.value;
}
return this.head;
}
toString() {
const arr = this.toArray();
return arr.toString();
}
toArray() {
const arr = [];
let current = this.head;
while (current) {
arr.push(current.value);
current = current.next;
}
return arr;
}
}
export default LinkedList;