-
Notifications
You must be signed in to change notification settings - Fork 0
/
Linked_List.js
112 lines (103 loc) · 2.03 KB
/
Linked_List.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
/**
* 单向链表的 js 实现
*/
/**
* 单个链表节点
*/
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class LinkedList {
constructor(val = null) {
this.head = null;
this.length = 0;
if (val) {
this.head = new Node(val);
this.length = 1;
}
}
append(val) {
const node = new Node(val);
if (this.head === null) {
this.head = node;
} else {
let current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
this.length += 1;
}
removeAt(position) {
if (position >= this.length || position < 0) {
return null;
}
let current = this.head;
if (position === 0) {
this.head = current.next;
} else {
let index = 0;
let prev = null;
while (index < position) {
prev = current;
current = current.next;
index += 1;
}
prev.next = current.next;
}
this.length -= 1;
return current.val;
}
insert(position, val) {
if (position >= this.length || position < 0) {
return false;
}
const node = new Node(val);
if (position === 0) {
node.next = this.head;
this.head = node;
} else {
let index = 0;
let current = this.head;
let prev = null;
while (index < position) {
prev = current;
current = current.next;
index += 1;
}
node.next = current;
prev.next = node;
}
this.length += 1;
return true;
}
indexOf(val, start = 0) {
if (start >= this.length) {
return -1;
}
let index = 0;
let current = this.head;
while (index < this.length) {
if (current.val === val && index >= start) {
return index;
}
current = current.next;
index += 1;
}
return -1;
}
remove(val, start = 0) {
const index = this.indexOf(val, start);
return this.removeAt(index);
}
size() {
return this.length;
}
isEmpty() {
return !!this.length;
}
}