-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList.js
52 lines (44 loc) · 1.22 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
function Linkedlist() {
function Node(content) {
this.content = content;
this.next = this;
this.prev = this;
}
this.head = null;
this.tail = null;
this.add = function(content) {
if (!this.head) {
this.head = this.tail = new Node(content);
}
else {
this.tail.next = new Node(content);
this.tail.next.prev = this.tail;
this.tail = this.tail.next;
this.tail.next = this.head;
this.head.prev = this.tail;
}
}
this.move_to_front = function(node) {
if (node === this.head) {
return;
}
let temp = this.head;
let isTailNode = false;
while (temp.next !== node)
temp = temp.next;
if (temp.next === this.tail)
isTailNode = true;
if(!isTailNode){
temp.next = node.next;
node.next.prev = temp;
}
else{
this.tail = this.tail.prev;
}
node.next = this.head;
this.head.prev = node;
this.head = node;
this.tail.next = this.head;
this.head.prev = this.tail;
}
}