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

leetcode Implement Queue using Stacks

时间:2015-11-22 23:28:05      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.

Notes:

    • You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
    • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
    • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

不难,想明白就好,貌似之前看到过这样的题目;一个栈用来存放push的东西,每次需要pop或者peek的时候,再将该栈的所有数据移到另外一个栈里。

 

 1 class Queue {
 2 public:
 3     stack<int> Squeue1;
 4     stack<int> Squeue2;
 5     // Push element x to the back of queue.
 6     void push(int x) {
 7         Squeue1.push(x);
 8     }
 9 
10     // Removes the element from in front of queue.
11     void pop(void) {
12             
13             int q;
14             if(Squeue2.empty()){
15             while(!Squeue1.empty()){
16             q=Squeue1.top();
17             Squeue2.push(q);
18             Squeue1.pop();
19             }
20             }
21             Squeue2.pop();
22         }
23         
24   
25 
26     // Get the front element.
27     int peek(void) {
28             int p,q;
29             if(Squeue2.empty()){
30             while(!Squeue1.empty()){
31             q=Squeue1.top();
32             Squeue2.push(q);
33             Squeue1.pop();
34             }
35             }
36             p=Squeue2.top();
37             return p;
38     }
39 
40     // Return whether the queue is empty.
41     bool empty(void) {
42         if(Squeue1.empty()&&Squeue2.empty()) return true;
43         else return false;
44         
45     }
46 };

 

leetcode Implement Queue using Stacks

标签:

原文地址:http://www.cnblogs.com/LUO77/p/4986907.html

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