• Stack两栈实现队列


    比较简单。

    View Code
     1 //用两个栈实现队列
    2
    3 #include<iostream>
    4 using namespace std;
    5
    6 template<class Type> class Stack
    7 {
    8 private:
    9 int top;
    10 Type* elements;
    11 int maxSize;
    12 public:
    13 Stack(int sz=50):top(-1),maxSize(sz)
    14 {
    15 elements=new Type[sz];
    16 }
    17
    18 void push(const Type& x)
    19 {
    20 elements[++top]=x;
    21 }
    22
    23 Type& pop()
    24 {
    25 return elements[top--];
    26 }
    27
    28 Type& peek()
    29 {
    30 return elements[top];
    31 }
    32
    33 bool isEmpty()
    34 {
    35 return (top==-1)?true:false;
    36 }
    37 };
    38
    39 template<class Type> class Queue
    40 {
    41 private:
    42 Stack<Type> stack1;
    43 Stack<Type> stack2;
    44 public:
    45
    46
    47 void enQueue(const Type& x)
    48 {
    49 stack1.push(x);
    50 }
    51
    52 Type& deQueue()
    53 {
    54 if(stack2.isEmpty())
    55 {
    56 /* if(stack1.isEmpty())
    57 {
    58 throw runtime_error("Queue 为空!");
    59 }
    60 else */
    61 while(!stack1.isEmpty())
    62 {
    63 stack2.push(stack1.pop());
    64 }
    65 }
    66 return stack2.pop();
    67 }
    68
    69 Type& peek()
    70 {
    71 if(stack2.isEmpty())
    72 {
    73 /* if(stack1.isEmpty())
    74 {
    75 throw runtime_error("Queue 为空!");
    76 }
    77 else */
    78 while(!stack1.isEmpty())
    79 {
    80 stack2.push(stack1.pop());
    81 }
    82 }
    83 return stack2.peek();
    84 }
    85 };
    86
    87 int main()
    88 {
    89 Queue<string> queue;
    90 queue.enQueue("first");
    91 queue.enQueue("second");
    92 cout<<queue.peek()<<endl;
    93 queue.enQueue("second");
    94 queue.deQueue();
    95 queue.enQueue("third");
    96 cout<<queue.deQueue()<<endl;
    97 cout<<queue.deQueue()<<endl;
    98 return 0;
    99 }
  • 相关阅读:
    2018福大软工实践第六次作业
    2018福大软工实践第五次作业
    2018福大软工实践第四次作业
    2018福大软工实践第三次作业
    2018福大软工实践第二次作业
    团队现场编程实战(抽奖系统)
    团队Alpha版本冲刺(三)
    团队Alpha版本冲刺(二)
    团队Alpha版本冲刺(一)
    福大软工 · 第八次作业
  • 原文地址:https://www.cnblogs.com/YipWingTim/p/2250563.html
Copyright © 2020-2023  润新知