generated from github/codespaces-blank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedListWithTail.js
119 lines (95 loc) · 2.31 KB
/
linkedListWithTail.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
console.clear()
class Node {
constructor(value) {
this.value = value
this.next = null
}
}
class LinkedList {
constructor() {
this.head = null
this.tail = null
this.size = 0
}
isEmpty() {
return this.size === 0
}
getSize() {
return this.size
}
print() {
let curr = this.head
const list = []
while (curr !== null) {
list.push(curr.value)
curr = curr.next
}
console.log("Linked List: ", list.join(" => "))
}
prepend(value) {
const node = new Node(value)
if (this.isEmpty()) {
this.head = node
this.tail = node
} else {
node.next = this.head
this.head = node
}
this.size++
}
append(value) {
const node = new Node(value)
if (this.isEmpty()) {
this.head = node
this.tail = node
} else {
this.tail.next = node
this.tail = node
}
this.size++
}
deleteFromHead() {
const removedNode = this.head
if (this.getSize() === 0) {
return null
} else if (this.getSize() === 1) {
this.head = null
this.tail = null
} else {
this.head = this.head.next
}
this.size--
return removedNode.value
}
deleteFromTail() {
const removedNode = this.tail
if (this.getSize() === 0) {
return null
} else if (this.getSize() === 1) {
this.head = null
this.tail = null
} else {
let prev = this.head
while (prev.next !== this.tail) {
prev = prev.next
}
prev.next = null
this.tail = prev
}
this.size--
return removedNode.value
}
}
// const linkedList = new LinkedList()
// console.log("Is Empty", linkedList.isEmpty())
// console.log("Size:", linkedList.getSize())
// linkedList.append(10)
// linkedList.append(20)
// linkedList.print()
// linkedList.prepend(5)
// linkedList.print()
// console.log(linkedList.deleteFromHead())
// linkedList.print()
// console.log(linkedList.deleteFromTail())
// linkedList.print()
module.exports = LinkedList