首页 > 其他 > 详细

【LeetCode】232 - Implement Queue using Stacks

时间:2015-08-02 15:00:48      阅读:191      评论: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 toppeek/pop from topsize, 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).
  •  1 class Queue {
     2 public:
     3     // Push element x to the back of queue.
     4     void push(int x) {
     5         stk.push(x);
     6     }
     7 
     8     // Removes the element from in front of queue.
     9     void pop(void) {
    10         stack<int> temp;
    11         while(stk.size()!=1){
    12             int x=stk.top();
    13             stk.pop();
    14             temp.push(x);
    15         }
    16         stk.pop();
    17         while(!temp.empty()){
    18             int x=temp.top();
    19             temp.pop();
    20             stk.push(x);
    21         }
    22     }
    23 
    24     // Get the front element.
    25     int peek(void) {
    26         stack<int> temp;
    27         while(stk.size()!=1){
    28             int x=stk.top();
    29             stk.pop();
    30             temp.push(x);
    31         }
    32         int x=stk.top();
    33         while(!temp.empty()){
    34             int x=temp.top();
    35             temp.pop();
    36             stk.push(x);
    37         }
    38         return x;
    39     }
    40 
    41     // Return whether the queue is empty.
    42     bool empty(void) {
    43         return stk.empty();
    44     }
    45 private:
    46     stack<int> stk;
    47 };

     

【LeetCode】232 - Implement Queue using Stacks

原文:http://www.cnblogs.com/irun/p/4695636.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!