zoukankan      html  css  js  c++  java
  • LeetCode OJ:Implement Queue using Stacks(栈实现队列)

    比较典型的一个题目,easy,不过可以有许多实现方式。 

    这里用的方式是每次pop完成之后再将stack2中的内容立即倒回stack1中。但是其他的实现也可以不是这样,可以是需要push的时候检查再,如果内容在stack2中,这时候将其倒回在进行push。这里采取第一种比较笨的方法,代码如下所示:

     1 class Queue {
     2 public:
     3     // Push element x to the back of queue.
     4     void push(int x) {
     5         s1.push(x);
     6     }
     7 
     8     // Removes the element from in front of queue.
     9     void pop(void) {
    10         while(!s1.empty()){
    11             s2.push(s1.top());
    12             s1.pop();
    13         }
    14         s2.pop();
    15         while(!s2.empty()){
    16             s1.push(s2.top());
    17             s2.pop();
    18         }
    19     }
    20 
    21     // Get the front element.
    22     int peek(void) {
    23         while(!s1.empty()){
    24             s2.push(s1.top());
    25             s1.pop();
    26         }
    27         int ret = s2.top();
    28         while(!s2.empty()){
    29             s1.push(s2.top());
    30             s2.pop();
    31         }
    32         return ret;
    33     }
    34 
    35     // Return whether the queue is empty.
    36     bool empty(void) {
    37         return s1.empty();
    38     }
    39 private:
    40     stack<int> s1;
    41     stack<int> s2;
    42 };
  • 相关阅读:
    字符串动手动脑
    类与对象课后思考
    java动手动脑课后思考题
    java思考题
    《大道至简第二章读后感》
    从命令行接收多个数字,求和之后输出结果
    《大道至简》读后感
    团队项目成员和题目
    软件工程个人作业04
    软件工程个人作业03
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/5014088.html
Copyright © 2011-2022 走看看