#leetCode brush title documentary Day7

https://leetcode-cn.com/problems/implement-stack-using-queues/

Queue implementation using the following stack:

push (x) - x elements onto the stack
pop () - remove the top of the stack
top () - Gets the top element
empty () - Returns whether the stack is empty


note:

You can only use the basic operation of the queue - that is, push to back, peek / pop from front, size, and is empty of these operations are legal.
The language you are using may not support queue. You can use the list or the deque (deque) to simulate a queue, the queue as long as the operation to the standard.
You may assume that all operations are valid (for example, to an empty stack does not call the pop operation or top).

 

Chicken dishes to try:

This is a problem with simulation queue stack, because yesterday the topic so that they are not confused, it is quite easy to do.

Over and over is quite happy!

 

 1 class MyStack {
 2 public:
 3     /** Initialize your data structure here. */
 4     queue<int> main;
 5     queue<int> b;
 6     MyStack() {
 7         
 8     }
 9     
10     /** Push element x onto stack. */
11     void push(int x) {
12          main.push(x);
13     }
14     
15     /** Removes the element on top of the stack and returns that element. */
16     int pop() {
17         while (main.size() > 1) {
18             b.push(main.front());
19             main.pop();
20         }
21         int result = main.front();
22         main.pop();
23         while (!b.empty()) {
24             main.push(b.front());
25             b.pop();
26         }
27         return result;
28     }
29     
30     /** Get the top element. */
31     int top() {
32         while (main.size() > 1) {
33             b.push(main.front());
34             main.pop();
35         }
36         int result = main.front();
37         b.push(main.front());
38         main.pop();
39         while (!b.empty()) {
40             main.push(b.front());
41             b.pop();
42         }
43         return result;
44     }
45     
46     /** Returns whether the stack is empty. */
47     bool empty() {
48         if (main.empty() && b.empty()) {
49             return true;
50         }
51         return false;
52     }
53 };
54 
55 /**
56  * Your MyStack object will be instantiated and called as such:
57  * MyStack* obj = new MyStack();
58  * obj->push(x);
59  * int param_2 = obj->pop();
60  * int param_3 = obj->top();
61  * bool param_4 = obj->empty();
62  */

 

 

 

 

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/implement-stack-using-queues
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Guess you like

Origin www.cnblogs.com/xyy999/p/11795220.html