|
| 1 | +<h2><a href="https://leetcode.com/problems/implement-stack-using-queues">225. Implement Stack using Queues</a></h2><h3>Easy</h3><hr><p>Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (<code>push</code>, <code>top</code>, <code>pop</code>, and <code>empty</code>).</p> |
| 2 | + |
| 3 | +<p>Implement the <code>MyStack</code> class:</p> |
| 4 | + |
| 5 | +<ul> |
| 6 | + <li><code>void push(int x)</code> Pushes element x to the top of the stack.</li> |
| 7 | + <li><code>int pop()</code> Removes the element on the top of the stack and returns it.</li> |
| 8 | + <li><code>int top()</code> Returns the element on the top of the stack.</li> |
| 9 | + <li><code>boolean empty()</code> Returns <code>true</code> if the stack is empty, <code>false</code> otherwise.</li> |
| 10 | +</ul> |
| 11 | + |
| 12 | +<p><b>Notes:</b></p> |
| 13 | + |
| 14 | +<ul> |
| 15 | + <li>You must use <strong>only</strong> standard operations of a queue, which means that only <code>push to back</code>, <code>peek/pop from front</code>, <code>size</code> and <code>is empty</code> operations are valid.</li> |
| 16 | + <li>Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.</li> |
| 17 | +</ul> |
| 18 | + |
| 19 | +<p> </p> |
| 20 | +<p><strong class="example">Example 1:</strong></p> |
| 21 | + |
| 22 | +<pre> |
| 23 | +<strong>Input</strong> |
| 24 | +["MyStack", "push", "push", "top", "pop", "empty"] |
| 25 | +[[], [1], [2], [], [], []] |
| 26 | +<strong>Output</strong> |
| 27 | +[null, null, null, 2, 2, false] |
| 28 | + |
| 29 | +<strong>Explanation</strong> |
| 30 | +MyStack myStack = new MyStack(); |
| 31 | +myStack.push(1); |
| 32 | +myStack.push(2); |
| 33 | +myStack.top(); // return 2 |
| 34 | +myStack.pop(); // return 2 |
| 35 | +myStack.empty(); // return False |
| 36 | +</pre> |
| 37 | + |
| 38 | +<p> </p> |
| 39 | +<p><strong>Constraints:</strong></p> |
| 40 | + |
| 41 | +<ul> |
| 42 | + <li><code>1 <= x <= 9</code></li> |
| 43 | + <li>At most <code>100</code> calls will be made to <code>push</code>, <code>pop</code>, <code>top</code>, and <code>empty</code>.</li> |
| 44 | + <li>All the calls to <code>pop</code> and <code>top</code> are valid.</li> |
| 45 | +</ul> |
| 46 | + |
| 47 | +<p> </p> |
| 48 | +<p><strong>Follow-up:</strong> Can you implement the stack using only one queue?</p> |
0 commit comments