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
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
20
28
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
21
29
*/
30
+
/*
31
+
Thoughts:
32
+
Use 2 stacks:
33
+
Stack: hold items in regular stack order
34
+
ReverseStack: hold items in the queue order.
35
+
36
+
- Add: pure from reverseStack into stack, add item, and pure back into reverseStack.
37
+
- Remove: remove from reverseStack
38
+
- peek, empty are trivial
39
+
*/
40
+
classMyQueue {
41
+
Stack<Integer> stack;
42
+
Stack<Integer> reverseStack;
43
+
/** Initialize your data structure here. */
44
+
publicMyQueue() {
45
+
stack = newStack<>();
46
+
reverseStack = newStack<>();
47
+
}
48
+
49
+
/** Push element x to the back of queue. */
50
+
publicvoidpush(intx) {
51
+
while (!reverseStack.isEmpty()) {
52
+
stack.push(pop());
53
+
}
54
+
stack.push(x);
55
+
56
+
// Pure back
57
+
while (!stack.isEmpty()) {
58
+
reverseStack.push(stack.pop());
59
+
}
60
+
}
61
+
62
+
/** Removes the element from in front of queue and returns that element. */
0 commit comments