LeetCode 232. Implement Queue using Stacks

和225类似,queue和stack的性质正好相反,因此在push时要进行处理。

维护两个stack:stk和tmp,stk存放与queue相反的顺序,比如queue为:1、4、5,stk为:5、4、1,这样stk.top()会一直等于queue.front()。

每次push进一个数x时,先把stk内的数全push进tmp中,再把x压入stk,最后把tmp中的数全push进stk,这样就保证了x在stk的栈底。

 1 class Queue {
 2 public:
 3     // Push element x to the back of queue.
 4     void push(int x) {
 5         while(!stk.empty()){
 6             tmp.push(stk.top());
 7             stk.pop();
 8         }
 9         stk.push(x);
10         while(!tmp.empty()){
11             stk.push(tmp.top());
12             tmp.pop();
13         }
14     }
15 
16     // Removes the element from in front of queue.
17     void pop(void) {
18         stk.pop();
19     }
20 
21     // Get the front element.
22     int peek(void) {
23         return stk.top();
24     }
25 
26     // Return whether the queue is empty.
27     bool empty(void) {
28         return stk.empty();
29     }
30 private:
31     stack<int> stk, tmp;
32 };

 

posted @ 2016-04-04 20:31  co0oder  阅读(153)  评论(0编辑  收藏  举报