-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueueUsingStack.ts
More file actions
94 lines (75 loc) · 1.56 KB
/
Copy pathqueueUsingStack.ts
File metadata and controls
94 lines (75 loc) · 1.56 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/**
* 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()
*/
class Stack {
stack: number[];
constructor() {
this.stack = [];
}
push(item: number) {
return this.stack.push(item);
}
pop() {
return this.stack.pop();
}
peek() {
return this.stack[this.length - 1];
}
get length() {
return this.stack.length;
}
isEmpty() {
return this.length === 0;
}
}
// Approach 1: Using 2 stacks
// Push: O(n), Pop/Peek/isEmpty: O(1)
class MyQueue {
firstStack: Stack;
secondStack: Stack;
top: number;
constructor() {
this.firstStack = new Stack();
this.secondStack = new Stack();
}
// Time: O(n)
// Space: O(n)
enqueue(item: number) {
// Save the first item of stack to top
if (this.firstStack.isEmpty()) {
this.top = item;
}
// Create the original stack
while (!this.firstStack.isEmpty()) {
this.secondStack.push(this.firstStack.pop());
}
this.secondStack.push(item);
// Reverse the stack to maintain the order FIFO of a queue
while (!this.secondStack.isEmpty()) {
this.firstStack.push(this.secondStack.pop());
}
}
dequeue() {
const result = this.firstStack.pop();
if (!this.firstStack.isEmpty()) {
this.top = this.firstStack.peek();
}
return result;
}
peek() {
return this.top;
}
isEmpty() {
return this.firstStack.isEmpty();
}
}
const test = new MyQueue();
test.enqueue(1);
test.enqueue(2);
test.peek();
console.log(test.peek());