-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked-list.js
136 lines (123 loc) · 3.02 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
125
126
127
128
129
130
131
132
133
134
135
136
class Node{
value = undefined;
prev = undefined;
next = undefined;
constructor(value, prev = undefined, next = undefined){
this.value = value;
this.prev = prev;
this.next = next;
}
}
class LinkedList{
head = undefined;
tail = undefined;
length = 0;
constructor(value = undefined){
if(value != undefined){
this.head = new Node(value, undefined, undefined);
this.length = 1;
}
else{
this.head = undefined;
this.length = 0;
}
this.tail = undefined;
}
add(value){
if(this.head == undefined){
this.head = new Node(value, undefined, undefined);
}
else if(this.tail == undefined){
this.tail = new Node(value, this.head, undefined);
this.head.next = this.tail;
}
else{
this.tail.next = new Node(value, this.tail, undefined);
this.tail = this.tail.next;
}
this.length ++;
}
shift(){
this.head = this.head.next;
this.length --;
}
pop(){
if(this.length == 1){
this.shift();
}
else{
this.tail.prev = undefined;
this.tail = this.tail.prev;
this.length --;
}
}
remove(n){
if(n < 0){
n = this.length + n;
}
if(this.length == 0){
throw "List is empty";
}
if(n >= this.length){
throw "Index is bigger than length";
}
if(n == 0){
this.shift();
}
else if(n == this.length - 1){
this.pop();
}
else if(n < this.length / 2){
let node = this.head;
for(let _ = 0; _ < n; _ ++){
node = node.next;
}
node.next.prev = node.prev;
node.prev.next = node.next;
this.length --;
}
else{
let node = this.tail;
for(let _ = this.length - 1; _ > n; _ --){
node = node.prev;
}
node.next.prev = node.prev;
node.prev.next = node.next;
this.length --;
}
}
getNode(n){
if(n < 0){
n = this.length + n;
}
if(this.length == 0){
throw "List is empty";
}
if(n >= this.length){
throw "Index is bigger than length";
}
if(n == 0){
return this.head;
}
else if(n == this.length - 1){
return this.tail;
}
else if(n < this.length / 2){
let node = this.head;
for(let _ = 0; _ < n; _ ++){
node = node.next;
}
return node;
}
else{
let node = this.tail;
for(let _ = this.length - 1; _ > n; _ --){
node = node.prev;
}
return node;
}
}
get(n){
return this.getNode(n);
}
}