代码随想录算法训练营第九天| 232.用栈实现队列 225. 用队列实现栈
232.用栈实现队列
注意:
1,构造函数不需要
2,需要有两个成员变量 in out
代码:
1 class MyQueue { 2 public: 3 stack<int> in; 4 stack<int>out; 5 MyQueue() { 6 7 } 8 9 void push(int x) { 10 in.push(x); 11 } 12 13 int pop() { 14 if (out.empty()) 15 { 16 while (in.empty() != true) 17 { 18 out.push(in.top()); 19 in.pop(); 20 } 21 } 22 23 int result = out.top(); 24 out.pop(); 25 return result; 26 } 27 28 int peek() { 29 int result = pop(); 30 out.push(result); 31 32 return result; 33 } 34 35 bool empty() { 36 if (out.empty() && in.empty()) 37 return true; 38 39 return false; 40 } 41 }; 42 43 /** 44 * Your MyQueue object will be instantiated and called as such: 45 * MyQueue* obj = new MyQueue(); 46 * obj->push(x); 47 * int param_2 = obj->pop(); 48 * int param_3 = obj->peek(); 49 * bool param_4 = obj->empty(); 50 */
225. 用队列实现栈
两种方式
1,两个队列,一个把所有的信息,除了最后一个,都放进另一个队列里面,然后在还回去
2,一个队列,所有的信息都在过一遍
两个队列代码:
1 class MyStack { 2 public: 3 std::queue<int> myqueue; 4 5 MyStack() { 6 7 } 8 9 void push(int x) { 10 myqueue.push(x); } 11 12 int pop() { 13 int size = myqueue.size(); 14 size--; 15 16 while (size--) 17 { 18 int cur = myqueue.front(); 19 myqueue.push(cur); 20 myqueue.pop(); 21 22 } 23 24 int result = myqueue.front(); 25 myqueue.pop(); 26 27 return result; 28 } 29 30 int top() { 31 return myqueue.back(); 32 33 } 34 35 bool empty() { 36 return myqueue.empty(); 37 } 38 };
一个队列代码
1 class MyStack { 2 public: 3 std::queue<int> myqueue; 4 5 MyStack() { 6 7 } 8 9 void push(int x) { 10 myqueue.push(x); } 11 12 int pop() { 13 int size = myqueue.size(); 14 while (size != 1) 15 { 16 int cur = myqueue.front(); 17 myqueue.pop(); 18 myqueue.push(cur); 19 size--; 20 } 21 22 23 int result = myqueue.front(); 24 myqueue.pop(); 25 26 return result; 27 } 28 29 int top() { 30 return myqueue.back(); 31 32 } 33 34 bool empty() { 35 return myqueue.empty(); 36 } 37 }; 38 39 /** 40 * Your MyStack object will be instantiated and called as such: 41 * MyStack* obj = new MyStack(); 42 * obj->push(x); 43 * int param_2 = obj->pop(); 44 * int param_3 = obj->top(); 45 * bool param_4 = obj->empty(); 46 */