Leetcode 232 Implement Queue using Stacks STL

本题用两个栈实现队列,用栈的基本操作去实现队列的所有基本操作push(),pop(),peek()以及empty()

sa作为输入栈,sb作为输出栈,将sa输入元素的反转过来放到sb中

push与sa有关,而pop(),peek()与sb有关,即将sa输入元素出栈放到sb中(函数move).

为此,只有两个栈为空才能让队列为空

 1 class Queue {
 2 public:
 3     // Push element x to the back of queue.
 4     stack<int> sa;
 5     stack<int> sb;
 6     void move(){
 7         while(!sa.empty()){
 8             sb.push(sa.top());
 9             sa.pop();
10         }
11     }
12     void push(int x) {
13         sa.push(x);
14     }
15 
16     // Removes the element from in front of queue.
17     void pop(void) {
18         if(!sb.empty()) sb.pop();
19         else{
20             move();
21             sb.pop();
22         }
23     }
24 
25     // Get the front element.
26     int peek(void) {
27         if(!sb.empty()) return sb.top();
28         else{
29             move();
30             return sb.top();
31         }
32 
33     }
34 
35     // Return whether the queue is empty.
36     bool empty(void) {
37         return sa.empty() && sb.empty();
38     }
39 };
原文地址:https://www.cnblogs.com/onlyac/p/5232161.html