forked from OperationCode/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackUsingQueue.js
More file actions
45 lines (33 loc) · 941 Bytes
/
StackUsingQueue.js
File metadata and controls
45 lines (33 loc) · 941 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
import Queue from "./Queue";
import Stack from "../stack/Stack";
export default class StackQ {
constructor() {
this.store = new Queue();
}
// The idea here is to make insertion slow and peeking and popping fast.
// We keep the items in the Queue in the reverse of the order the usually would be in.
//
isEmpty() {
return this.store.isEmpty();
}
peek() {
return this.store.peek();
}
push(el) {
var s = this.store.length();
this.store.enqueue(el);
// we want the most recently added object to be next item that is popped. We need to remove all the other items and
// queue them up so they are newer than the current item.
for (var i = 0; i < s; i++) {
this.store.enqueue(this.store.peek());
this.store.dequeue();
}
return this.store.peek();
}
pop() {
return this.store.dequeue();
}
toString() {
return this.store.toString();
}
}