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 }
  • 相关阅读:
    Wannafly挑战赛13 C:zzf的好矩阵(思维)
    Wannafly挑战赛13 B:Jxc军训(逆元)
    TZOJ 1221 Tempter of the Bone(回溯+剪枝)
    AtCoder Regular Contest 092 C
    TZOJ 3030 Courses(二分图匹配)
    TOJ 2778 数据结构练习题――分油问题(广搜和哈希)
    PAT L3-001 凑零钱(01背包dp记录路径)
    [HNOI2009]通往城堡之路
    [HNOI2006]潘多拉的宝盒
    [bzoj4361]isn
  • 原文地址:https://www.cnblogs.com/Juntaran/p/5819410.html
Copyright © 2011-2022 走看看