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
46 lines (42 loc) · 892 Bytes
/
Copy pathExercise_2.js
File metadata and controls
46 lines (42 loc) · 892 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
46
class StackAsLinkedList {
static stackNode = class {
constructor(d) {
//Constructor here
this.data = d;
this.next = null;
}
};
constructor() {
this.root = null; // top of the stack
}
isEmpty() {
return this.root === null;
}
push(data) {
const newNode = new StackAsLinkedList.stackNode(data);
newNode.next = this.root;
this.root = newNode;
}
pop() {
if (this.isEmpty()) {
console.log("Stack Underflow");
return 0;
}
const popData = this.root.data;
this.root = this.root.next;
return popData;
}
peek() {
if (this.isEmpty()) {
console.log("Stack Empty");
return 0;
}
return this.root.data;
}
}
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());