码迷,mamicode.com
首页 > 其他好文 > 详细

QueueWithTwoStacks

时间:2015-08-02 20:06:21      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

用两个栈实现队列的push() 和 pop()

#include <iostream>
#include <stack>
#include <stdexcept>
using namespace std;

template <class T>
class CQueue
{
    public:
      CQueue() {};
      ~CQueue() {};

      void appendTail(const T& node);
      T deleteHead();

    private:
      stack<T> stack1;
      stack<T> stack2;
};

template <class T>
void CQueue<T>::appendTail(const T& node)
{
    stack1.push(node);
}

template <class T>
T CQueue<T>::deleteHead()
{
    if (stack2.empty())
    {
        while (!stack1.empty())
        {
            T& tmp = stack1.top();
            stack1.pop();
            stack2.push(tmp);
        }


    }
        if (stack2.empty())
        {
            throw runtime_error(" queue is empty");
        }



        T head = stack2.top();
        stack2.pop();

        return head;
}    

void  Test(int actual, int excepted)
{
    if (actual == excepted)
        cout << "Test passed.\n";
    else
        cout << "Test failed.\n";
}

int main()
{
   try {
    CQueue<int> queue;
    queue.appendTail(1);
    queue.appendTail(2);
    queue.appendTail(3);

    int head = queue.deleteHead();
    Test(head,1);

    head = queue.deleteHead();
    Test(head,2);

    queue.appendTail(4);
    head = queue.deleteHead();
    Test(head,3);

    queue.appendTail(5);
    head = queue.deleteHead();
    Test(head,4);

    head = queue.deleteHead();
    Test(head,5);
   }

   catch (runtime_error err) {
        cout << err.what() << endl;
    }

    return 0;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

QueueWithTwoStacks

标签:

原文地址:http://blog.csdn.net/nizhannizhan/article/details/47209651

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!