forked from super30admin/PreCourse-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExercise_2.js
More file actions
45 lines (38 loc) · 907 Bytes
/
Exercise_2.js
File metadata and controls
45 lines (38 loc) · 907 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
39
40
41
42
43
44
45
class StackAsLinkedList {
static stackNode = class {
constructor(d) {
this.data = d;
this.next = null;
}
};
constructor() {
this.top = null;
}
isEmpty() {
return this.top === null;
}
push(data) {
const newNode = new StackAsLinkedList.stackNode(data);
newNode.next = this.top;
this.top = newNode;
}
pop() {
if (this.isEmpty()) {
console.log("Stack Underflow");
return 0;
}
const poppedValue = this.top.data;
this.top = this.top.next;
return poppedValue;
}
peek() {
return this.isEmpty() ? null : this.top.data;
}
}
// Driver code
const sll = new StackAsLinkedList();
sll.push(10);
sll.push(20);
sll.push(30);
console.log(sll.pop() + " popped from stack");
console.log("Top element is " + sll.peek());