forked from super30admin/Design-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimplement-queue-using-stacks.ts
More file actions
59 lines (49 loc) · 1.05 KB
/
implement-queue-using-stacks.ts
File metadata and controls
59 lines (49 loc) · 1.05 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
// Time Complexity, Amortized - O(1), worst case - O(n), where n is number os element inserted elements
// Space Complexity: O(n), where n is size of queue - number of inserted elements
class MyQueue {
private in: Stack;
private out: Stack;
constructor() {
this.in = new Stack();
this.out = new Stack();
}
push(x: number): void {
this.in.push(x);
}
pop(): number {
this.peek();
return this.out.pop();
}
peek(): number {
if (this.out.isEmpty()) {
while (!this.in.isEmpty()) {
const poppedElement = this.in.pop();
this.out.push(poppedElement);
}
}
return this.out.peek();
}
empty(): boolean {
return this.in.isEmpty() && this.out.isEmpty();
}
}
class Stack {
private stack: number[];
constructor() {
this.stack = [];
}
push(val: number): void {
this.stack.push(val);
}
isEmpty(): boolean {
return this.stack.length === 0;
}
pop(): number | null {
if (this.isEmpty()) return;
return this.stack.pop();
}
peek(): number | null {
if (this.isEmpty()) return;
return this.stack[this.stack.length - 1];
}
}