-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem_3.4.js
41 lines (41 loc) · 964 Bytes
/
problem_3.4.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
// Problem #3.4:
// Implement a MyQueue class which implements a queue using two stacks.
class MyQueue {
constructor() {
this.stack1 = new Stack(); // makes use of an auxiliar Stack class
this.stack2 = new Stack();
}
push(x) {
this.stack1.push(x);
}
pop() {
while (!this.stack1.isEmpty()) {
this.stack2.push(this.stack1.pop());
}
let elem = this.stack2.pop();
while (!this.stack2.isEmpty()) {
this.stack1.push(this.stack2.pop());
}
return elem;
}
peek() {
while (!this.stack1.isEmpty()) {
this.stack2.push(this.stack1.pop());
}
let elem = this.stack2.top();
while (!this.stack2.isEmpty()) {
this.stack1.push(this.stack2.pop());
}
return elem;
}
empty() {
return this.stack1.isEmpty();
}
}
let queue = new MyQueue();
queue.push(3);
queue.push(4);
queue.push(5);
console.log(queue.peek()); // 3
console.log(queue.pop()); // 3
console.log(queue.peek()); // 4