• 用两个栈实现一个队列


    用两个栈实现一个队列

     1 #include<iostream>
     2 #include<stdlib.h>
     3 #include<stack>
     4 using namespace std;
     5 
     6 template <typename T>class CQueue
     7 {
     8 public:
     9     CQueue(void);
    10     ~CQueue(void);
    11     void appendtail(const T& node);
    12     T deleteHead();
    13 private:
    14     stack<T> stack1;
    15     stack<T> stack2;
    16 
    17 };
    18 
    19 //构造函数
    20 template <typename T> CQueue<T>::CQueue(void)
    21 {
    22 }
    23 
    24 //析构函数
    25 template <typename T> CQueue<T>::~CQueue(void)
    26 {
    27 }
    28 
    29 //插入元素
    30 template <typename T> void CQueue<T>::appendtail(const T& node)
    31 {
    32     stack1.push(node);
    33 }
    34 
    35 //删除元素并返回
    36 template <typename T> T CQueue<T>::deleteHead()
    37 {
    38     if(stack2.size()<=0)
    39     {
    40         while(stack1.size()>0)
    41         {
    42             stack2.push(stack1.top());
    43             stack1.pop();
    44         }
    45     }
    46     if(stack2.size()==0)
    47         throw new exception("队列为空");
    48     T head=stack2.top();
    49     stack2.pop();
    50     return head;
    51 }
    52 
    53 void main()
    54 {
    55     CQueue<int> queue;
    56     queue.appendtail(1);
    57     queue.appendtail(2);
    58     queue.appendtail(3);
    59     queue.appendtail(4);
    60     int len=4;
    61     while(len>0)
    62     {
    63         cout<<queue.deleteHead()<<endl;
    64         --len;
    65     }
    66     system("pause");
    67 }
  • 相关阅读:
    [NOI2009]管道取珠
    Rebalance再均衡
    生产者分区写入策略
    Kafka事务
    幂等性
    消费者组
    Kafka中的重要概念
    偏移量offset
    服务注册和发现的意思,Spring cloud如何实现?
    负载平衡的意义
  • 原文地址:https://www.cnblogs.com/wxdjss/p/5450969.html
Copyright © 2020-2023  润新知