码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 232. Implement Queue using Stacks

时间:2016-04-04 20:55:45      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:

和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 };

 

LeetCode 232. Implement Queue using Stacks

标签:

原文地址:http://www.cnblogs.com/co0oder/p/5352805.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!