-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0x02-doubly_linked_list.js
More file actions
executable file
·83 lines (76 loc) · 1.79 KB
/
Copy path0x02-doubly_linked_list.js
File metadata and controls
executable file
·83 lines (76 loc) · 1.79 KB
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
#!/usr/bin/node
/** instantiates a new node */
class Node{
constructor(value) {
this.value = value
this.prev = null
this.next = null
}
}
/** implement doubly linked list and its methods */
class doubly_linked_list{
constructor() {
this.head = null
this.tail = null
this.size = 0
}
/**
* adds a node to the end of list
* Time Complexity: O(1)
*/
append_node(value) {
let new_node = new Node(value);
if(!this.head){
this.head = new_node
this.tail = new_node
this.size++
return
}
new_node.prev = this.tail
this.tail.next = new_node
this.tail = new_node
}
/**
* adds a node with value v at specific index idx
* Time complexity: O(n)
* NB optimize to transverse via quickest side - from tail/head
* */
insertAt(idx, v) {
let new_node = new Node(v)
let i = 0
let current = this.head
let prv = null
if(idx == 0) {
new_node.next = this.head
this.head.prev = new_node
this.head = this.head.prev
this.size++
return
}
while(i < idx) {
prv = current
current = current.next
i++
}
new_node.next = current
new_node.prev = prv
prv.next = new_node
current.prev = new_node
this.size++
}
print_list(){
let current = this.head
while(current){
console.log(current.value)
current = current.next
}
}
}
let dll = new doubly_linked_list
dll.append_node(23)
dll.append_node(2)
dll.append_node(22)
dll.insertAt(0,9)
dll.insertAt(1, 9.5)
dll.insertAt(1, 9.6)
dll.print_list()