-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimplement-queue-using-stacks.js
83 lines (67 loc) · 1.51 KB
/
implement-queue-using-stacks.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
Implement Queue Using Stacks (https://leetcode.com/problems/implement-queue-using-stacks/)
- Implemnet a first-in-first-out (FIFO) queue using only 2 stacks.
- The implemented queue should support all the functions of a normal queue:
- empty: Return true is the queue is empty, false otherwise
- peek: Return the element at the front of the queue
- push: Push elements to the back of the queue
- pop: Remove elements from the front of the queue
Constraints:
- Only use the standard operations of a stack
- push to top
- pop from top
- peek from top
- size
- empty
*/
// ---- Solution ----
class Stack {
constructor() {
this.stack = [];
}
empty() {
return this.stack.length === 0;
}
size() {
return this.stack.length;
}
push(value) {
this.stack.push(value);
}
pop() {
return this.stack.pop();
}
peek() {
return this.stack[this.size() - 1];
}
}
class MyQueue {
constructor() {
this.stack = new Stack();
this.reversedStack = new Stack();
}
_transcribe() {
while (this.stack.size()) {
this.reversedStack.push(this.stack.pop());
}
}
empty() {
return this.stack.empty() && this.reversedStack.empty();
}
push(value) {
this.stack.push(value);
}
pop() {
if (!this.reversedStack.size()) {
this._transcribe();
}
return this.reversedStack.pop();
}
peek() {
if (!this.reversedStack.size()) {
this._transcribe();
}
return this.reversedStack.peek();
}
}
const myQueue = new MyQueue();