zoukankan      html  css  js  c++  java
  • 面试题7:用两个栈实现队列

    stack1负责如队列,stack2负责出队列,当stack2为空时,要将stack1的元素及时放入stack2

    两个队列也可以实现一个栈,P61

    写程序的时候出了两个问题:

    if (stack2.empty())
        {
            while (!stack1.empty())
            {
                stack2.push(stack1.top());
                stack1.pop();
            }
        }

    不要写成while(!stack1.empty() && !stack2.empty()),这样的话只会放入stack1中的一个元素

    另外模板函数前不要忘记加类型

    template <typename T> void CQueue<T>::appendTail(const T& node)

    template <typename T> T CQueue<T>::deleteHead()

    完整程序:

     1 #include <iostream>
     2 using namespace std;
     3 #include <stack>
     4 
     5 template <typename T> class CQueue
     6 {
     7 public:
     8     CQueue(void);
     9     ~CQueue(void);
    10 
    11     // 在队列末尾添加一个结点
    12     void appendTail(const T& node);
    13 
    14     // 删除队列的头结点
    15     T deleteHead();
    16 
    17 private:
    18     stack<T> stack1;
    19     stack<T> stack2;
    20 };
    21 
    22 template <typename T> CQueue<T>::CQueue(void)
    23 {
    24 }
    25 
    26 template <typename T> CQueue<T>::~CQueue(void)
    27 {
    28 }
    29 
    30 template <typename T> void CQueue<T>::appendTail(const T& node)
    31 {
    32     stack1.push(node);
    33 }
    34 
    35 template <typename T> T CQueue<T>::deleteHead()
    36 {
    37     if (stack2.empty())
    38     {
    39         while (!stack1.empty())
    40         {
    41             stack2.push(stack1.top());
    42             stack1.pop();
    43         }
    44     }
    45 
    46     if (stack2.size() == 0)
    47         throw new exception("queue is empty");
    48 
    49     T head = stack2.top();
    50     stack2.pop();
    51 
    52     return head;
    53 
    54 }
    55 
    56 void Test(char actual, char expected)
    57 {
    58     if (actual == expected)
    59         printf("Test passed.
    ");
    60     else
    61         printf("Test failed.
    ");
    62 }
    63 
    64 int main()
    65 {
    66     CQueue<char> queue;
    67 
    68     queue.appendTail('a');
    69     queue.appendTail('b');
    70     queue.appendTail('c');
    71 
    72     char head = queue.deleteHead();
    73     Test(head, 'a');
    74 
    75     head = queue.deleteHead();
    76     Test(head, 'b');
    77 
    78     queue.appendTail('d');
    79     head = queue.deleteHead();
    80     Test(head, 'c');
    81 
    82     queue.appendTail('e');
    83     head = queue.deleteHead();
    84     Test(head, 'd');
    85 
    86     head = queue.deleteHead();
    87     Test(head, 'e');
    88 
    89     system("pause");
    90     return 0;
    91 }
  • 相关阅读:
    使用批处理bat作为日期系统日期的前三天
    电脑桌面显示倒退
    BZOJ 2648/2716(SJY把件-KD_Tree)[Template:KD_Tree]
    yii使用寻呼功能
    宝付额度
    vs2010旗舰版产品密钥
    考察网贷平台是否正规,仅供参考。
    sql server 修改字段大小
    帕累托分析法
    帕累托分析法(Pareto Analysis)(柏拉图分析)
  • 原文地址:https://www.cnblogs.com/raichen/p/5635906.html
Copyright © 2011-2022 走看看