-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path4-stack-using-class.js
More file actions
104 lines (82 loc) · 2.21 KB
/
4-stack-using-class.js
File metadata and controls
104 lines (82 loc) · 2.21 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
================================================================
What is Stack:
-------------------
A LIFO data structure.
The last element added to the stack will be the first element
removed from the stack.
Where stacks are used?
------------------------
1) Managing function invocationn
2) Undo/Redo
3) Routing (the history obbject) is treated like a stack
Note:
------
There are many more ways to implement a stack.
Pushing Pseudocode:
-----------------------
1) The function should accept a value.
2) Create a new nonde with the value.
3) If there are no nnodes inn the stack, set the first and last
property to be the newly created node.
4) If there is at least one node, create a variable that stores the
current first property on the stack.
5) Reset the first property to be the newly created nnode
6) Set the next property on the node to bbe the previously created
variable
7) Increment the size of the stack by 1.
Popping Pseudocode:
-----------------------
1) If there are no nodes in the stack, return null.
2) Create a temporary varibale to store the first property on the
stack.
3) If there is only 1 nonde, set the first and last property to be
null.
4) If there is more than one node, set the first property to be
the next property on the current first.
5) Decrement the size by 1.
6) Return the value of the node removed.
================================================================
*/
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class Stack {
constructor() {
this.first = null;
this.last = null;
this.size = 0;
}
push(val) {
let newNode = new Node(val);
if (this.size === 0) {
this.first = newNode;
this.last = this.first;
} else {
let current = this.first;
this.first = newNode;
this.first.next = current;
}
return ++this.size;
}
pop() {
if (this.size === 0) return null;
let poppedNode = this.first;
if (this.size === 1) {
this.last = null;
}
this.first = this.first.next;
this.size -= 1;
return poppedNode;
}
}
let stack = new Stack();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50); // should be deleted first
console.log(stack);