-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimplement-queue-using-stacks.ts
More file actions
75 lines (61 loc) · 1.37 KB
/
Copy pathimplement-queue-using-stacks.ts
File metadata and controls
75 lines (61 loc) · 1.37 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
/*
* @lc app=leetcode id=232 lang=typescript
*
* [232] Implement Queue using Stacks
*/
// @lc code=start
class Stack {
private _list: Array<number> = []
push(...elements) {
this._list.push(...elements)
}
pop() {
return this._list.pop()
}
peek() {
return this._list[this._list.length-1]
}
isEmpty() {
return this._list.length == 0
}
get size() {
return this._list.length;
}
}
class MyQueue {
private _stack1 = new Stack();
private _stack2 = new Stack();
push(x: number): void {
this._stack1.push(x);
}
pop(): number {
this.swap(this._stack1, this._stack2)
const element = this._stack2.pop();
this.swap(this._stack2, this._stack1)
return element;
}
peek(): number {
this.swap(this._stack1, this._stack2)
const element = this._stack2.peek();
this.swap(this._stack2, this._stack1)
return element;
}
empty(): boolean {
return this._stack1.isEmpty();
}
swap(stack1, stack2) {
while(!stack1.isEmpty()) {
const element = stack1.pop()
stack2.push(element)
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* var obj = new MyQueue()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.peek()
* var param_4 = obj.empty()
*/
// @lc code=end