-
Notifications
You must be signed in to change notification settings - Fork 0
/
DoublyLinkedList.js
133 lines (128 loc) · 3.08 KB
/
DoublyLinkedList.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
class Node {
constructor(val) {
this.val = val;
this.prev = null;
this.next = null;
}
}
class SinglyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
push(value) {
let node = new Node(value);
if (!this.head) {
this.tail = node;
this.head = node;
} else {
this.tail.next = node;
node.prev = this.tail;
this.tail = node;
}
this.length++;
return this;
}
pop() {
if (!this.head)
return undefined;
let poppedNode = this.tail;
let prev = poppedNode.prev;
if (this.length === 1) {
this.head = null
this.tail = null
} else {
prev.next = null;
this.tail = prev
poppedNode.prev = null;
}
this.length--;
return poppedNode
}
shift() {
if (this.length === 0)
return undefined;
let oldHead = this.head;
if (this.length === 1) {
this.head = null;
this.tail = null;
}
let next = oldHead.next
this.head = next;
next.prev = null
oldHead.next = null;
this.length--;
return oldHead;
}
unshift(val) {
let newNode = new Node(val);
if (this.length === 0) {
this.head = newNode;
this.tail = newNode;
} else {
let currenHead = this.head;
newNode.next = currenHead;
currenHead.prev = newNode;
this.head = newNode;
}
this.length++;
return newNode;
}
get(index) {
let current;
let temp = Math.floor(this.length / 2);
if (index < temp) {
current = this.head
for (let i = 0; i < index; i++) {
current = current.next
}
} else {
current = this.tail
for(let i = this.length; i > index + 1; i-- ){
current = current.prev;
}
}
return current;
}
insert(index, val){
let newNode = new Node(val);
let prevNode = this.get(index-1);
let tempNext = prevNode.next;
newNode.next = tempNext;
newNode.prev = prevNode;
prevNode.next = newNode;
tempNext.prev = newNode;
this.length++;
return newNode;
}
set(index,val){
let node = this.get(index)
node.val = val
return this;
}
remove(index){
let currentNode = this.get(index);
let prevNode = currentNode.prev;
let nextNode = currentNode.next;
prevNode.next = nextNode;
nextNode.prev = prevNode;
currentNode.next = null;
currentNode.prev = null;
this.length--;
return currentNode;
}
}
let list = new SinglyLinkedList();
list.push(0);
list.push(1);
list.push(2);
list.push(3);
list.push(4);
list.push(5);
list.push(6);
list.push(7);
list.push(8);
list.push(9);
list.push(10);
list.push(11);