You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
🔥 Implement Stack using Queues 🔥 || 3 Solutions || Simple Fast and Easy || with Explanation
Solution - 1 Single Queue
import'dart:collection';
classMyStack {
// Runtime: 467 ms, faster than 50.00% of Dart online submissions for Implement Stack using Queues.// Memory Usage: 143 MB, less than 75.00% of Dart online submissions for Implement Stack using Queues.Queue<int> queue =Queue();
MyStack() {
this.queue;
}
voidpush(int x) {
queue.add(x);
for (int i =0; i < queue.length -1; i++) {
queue.add(queue.removeFirst());
}
}
intpop() {
return queue.removeFirst();
}
inttop() {
return queue.first;
}
boolempty() {
return queue.isEmpty;
}
}
Solution - 2 Double Queue
import'dart:collection';
classMyStack {
// Runtime: 469 ms, faster than 50.00% of Dart online submissions for Implement Stack using Queues.// Memory Usage: 143 MB, less than 50.00% of Dart online submissions for Implement Stack using Queues.Queue<int> queueOne =Queue();
Queue<int> queueTwo =Queue();
MyStack() {
this.queueOne;
this.queueTwo;
}
voidpush(int x) {
if (queueOne.isEmpty && queueTwo.isEmpty) {
queueOne.add(x);
} elseif (queueOne.isEmpty) {
queueOne.add(x);
while (queueTwo.isNotEmpty) {
queueOne.add(queueTwo.removeFirst());
}
} elseif (queueTwo.isEmpty) {
queueTwo.add(x);
while (queueOne.isNotEmpty) {
queueTwo.add(queueOne.removeFirst());
}
}
}
intpop() {
if (queueOne.isNotEmpty) {
return queueOne.removeFirst();
} elseif (queueTwo.isNotEmpty)
return queueTwo.removeFirst();
elsereturn-1;
}
inttop() {
if (queueOne.isNotEmpty) {
return queueOne.first;
} elseif (queueTwo.isNotEmpty)
return queueTwo.first;
elsereturn-1;
}
boolempty() {
return queueTwo.isEmpty && queueOne.isEmpty;
}
}
Bonus Solution - Go 😈
typeMyStackstruct {
queue []int
}
/** Initialize your data structure here. */funcConstructor() MyStack {
returnMyStack{ []int{} }
}
/** Push element x onto stack. */func (this*MyStack) Push(xint) {
this.queue=append(this.queue[:0], append([]int{x}, this.queue[0:]...)...) // prepend
}
/** Removes the element on top of the stack and returns that element. */func (this*MyStack) Pop() int {
temp:=this.queue[0]
this.queue=this.queue[1:]
returntemp
}
/** Get the top element. */func (this*MyStack) Top() int {
returnthis.queue[0]
}
/** Returns whether the stack is empty. */func (this*MyStack) Empty() bool {
returnlen(this.queue) ==0
}