zoukankan      html  css  js  c++  java
  • 剑指Offer05 用栈模拟队列

    添加了模板类应用

     1 /*************************************************************************
     2     > File Name: 05_StackMakeQueue.cpp
     3     > Author: Juntaran
     4     > Mail: JuntaranMail@gmail.com
     5     > Created Time: 2016年08月29日 星期一 19时32分12秒
     6  ************************************************************************/
     7 
     8 #include <stdio.h>
     9 #include <bits/stdc++.h>
    10 
    11 using namespace std;
    12 
    13 template<class T>
    14 class qStack
    15 {
    16 private:
    17     stack<T> stack1;
    18     stack<T> stack2;
    19     int size;
    20     
    21 public:
    22     qStack()
    23     {
    24         size = 0;
    25     }
    26     void push(T &node)
    27     {
    28         stack1.push(node);
    29         size = stack1.size();
    30     }
    31     T pop()
    32     {
    33         assert(this->size > 0);
    34         T ret = 0;
    35         if (this->size == 1)
    36         {
    37             ret = stack1.top();
    38             stack1.pop();
    39             this->size = 0;
    40             return ret;
    41         }
    42         if (this->size > 1)
    43         {
    44             while (stack1.size())
    45             {
    46                 stack2.push(stack1.top());
    47                 stack1.pop();
    48             }
    49             ret = stack2.top();
    50             stack2.pop();
    51             
    52             while (stack2.size())
    53             {
    54                 stack1.push(stack2.top());
    55                 stack2.pop();
    56             }
    57             this->size --;
    58             return ret;
    59         }
    60     }
    61 };
    62 
    63 
    64 int main()
    65 {
    66     qStack<int> quque;
    67     for (int i = 0; i < 5; i++)
    68     {
    69         cout << i << " push" << endl;
    70         quque.push(i);
    71     }
    72     for (int i = 1; i < 3; i++)
    73     {
    74         cout << quque.pop() << " pop" << endl;
    75     }
    76     for (int i = 5; i < 7; i++)
    77     {
    78         cout << i << " push" << endl;
    79         quque.push(i);
    80     }
    81     for (int i = 1; i < 3; i++)
    82     {
    83         cout << quque.pop() << " pop" << endl;
    84     }
    85     cout << endl;
    86 }
  • 相关阅读:
    POJ 2407 Relatives 欧拉函数
    HDU 4704 Sum 超大数幂取模
    HDU 4699 Editor 维护栈
    HDU 4696 Answers 水题
    HDU 4686 Arc of Dream 矩阵
    [转]高斯消元题集
    [转]计算几何题集
    POJ 2981 Strange Way to Express Integers 模线性方程组
    Linux 设置文件默认打开方式
    FZU 1402 猪的安家 中国剩余定理
  • 原文地址:https://www.cnblogs.com/Juntaran/p/5819410.html
Copyright © 2011-2022 走看看