-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.js
64 lines (54 loc) · 1.2 KB
/
stack.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
class Stack{
constructor(){
this.size = 0;
this.first = null;
this.last = null;
}
// push to stack
push(val){
let newNode = new Node(val);
if(!this.first){
this.first = newNode;
this.last = newNode;
}else{
newNode.next = this.first;
this.first = newNode;
}
this.size++;
return this.size;
}
// remove last item added
pop(){
if(!this.first) return null;
var temp = this.first;
if(this.first === this.last){
this.last = null;
}
this.first = this.first.next;
this.size--;
return temp.val;
}
// convert list to array
toArray(){
let curr = this.first;
let arr = []
while(curr){
arr.push(curr.val);
curr = curr.next;
}
return arr;
}
}
/////
class Node{
constructor(val){
this.val = val;
this.next = null;
}
}
let stack = new Stack();
stack.push('do job');
stack.push('rest');
stack.push('sleep');
stack.pop();
console.log(stack.toArray());