/
linked-list.js
124 lines (94 loc) · 2.39 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
113
114
115
116
117
118
119
120
121
122
123
124
const Node = require('./node');
class LinkedList {
constructor() {
this._head = null;
this._tail = null;
this.length = 0;
}
append(data) {
let node = new Node(data);
if(this._tail) {
node.prev = this._tail;
this._tail.next = node;
this._tail = node;
} else {
this._head = node;
this._tail = node;
}
this.length += 1;
return this;
}
head() {
return this._head ? this._head.data : this._head;
}
tail() {
return this._tail ? this._tail.data : this._tail;
}
find(index){
let count = 0;
let length = this.length;
let currNode = this._head;
while(length) {
if(index === count) return currNode;
length -= 1;
count += 1;
currNode = currNode.next;
}
return this;
}
at(index) {
return this.find(index).data;
}
insertAt(index, data) {
let currNode = this.find(index);
let newNode = new Node(data, currNode.prev, currNode);
currNode.prev.next = newNode;
currNode.prev = newNode;
this.length += 1;
return this;
}
isEmpty() {
return !Boolean(this.length);
}
clear() {
this._head = null;
this._tail = null;
this.length = 0;
return this;
}
deleteAt(index) {
let nextNode = this.find(index + 1);
let prevNode = this.find(index - 1);
nextNode.prev = prevNode;
prevNode.next = nextNode;
return this;
}
reverse() {
let currNode = this._head;
let length = this.length;
while(length){
let tmp = currNode.prev;
currNode.prev = currNode.next;
currNode.next = tmp;
currNode = currNode.prev;
length -= 1;
}
let tmp = this._head;
this._head = this._tail;
this._tail = tmp;
return this;
}
indexOf(data) {
let currNode = this._head;
let count = 0;
let length = this.length;
while(length) {
if(currNode.data === data) return count;
length -= 1;
count += 1;
currNode = currNode.next;
}
return -1;
}
}
module.exports = LinkedList;