-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.ts
More file actions
38 lines (30 loc) · 970 Bytes
/
stack.ts
File metadata and controls
38 lines (30 loc) · 970 Bytes
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
import LinkedList from '../linked-list/linked-list'
export default class Stack<T> {
constructor(public linkedList: LinkedList<T> = new LinkedList()) {}
isEmpty(): boolean {
// Stack is empty if its linked list doesn't have a head
return !this.linkedList.head
}
peek(): T | undefined | null {
if (this.isEmpty()) {
// If the linked is empty there is nothing to peek from
return null
}
// Read the value from the start of linked list
return this.linkedList.head?.value
}
push(value: T) {
// Add the new value at the start of the linked list
this.linkedList.prepend(value)
}
pop(): T | null {
const removeHead = this.linkedList.deleteHead()
return removeHead ? removeHead.value : null
}
toArray(): T[] {
return this.linkedList.toArray().map((linkListNode) => linkListNode.value)
}
toString(callback?: (value: T) => string): string {
return this.linkedList.toString(callback)
}
}