用两个队列实现一个栈

来源:互联网 发布:淘宝网店助理 编辑:程序博客网 时间:2024/06/01 07:29

queue.h

#include<iostream>#include<assert.h>using namespace std;template<typename T>struct Node{    template<class T>    friend class Queue;public:    Node(const T& x)        :_data(x)        , _next(NULL)    {}private:    T _data;    Node* _next;};template<class T>class Queue{public:    Queue()        :_QHead(NULL)        , _QTail(NULL)    {}    ~Queue()    {        while (_size != 0)        {            Node<T>* del = _QHead;            _QHead = _QHead->_next;            delete del;            _size--;        }    }    void Push(const T& x)   //队尾插入元素    {        assert(this);        if (_QHead == NULL)        {            _QHead = new Node<T>(x);            _QTail = _QHead;        }        else        {            Node<T>* tmp = new Node<T>(x);            _QTail->_next = tmp;            _QTail = tmp;        }        _size++;    }    void Pop()          //队头删除元素    {        assert(this);        if (_QHead == NULL)  //链表为空        {            return;        }        if (_QHead == _QTail)  //只有一个节点        {            delete _QHead;            _QHead = NULL;            _QTail = NULL;        }        else                  //有多个节点        {            Node<T>* del = _QHead;            _QHead = _QHead->_next;            delete del;        }        _size--;    }    bool Empty()  //判空    {        return _size == 0;    }    int Size()  //返回队列长度    {        return _size;    }    const T& Fornt() //返回队头元素    {        return _QHead->_data;    }    const T& Back()  //返回队尾元素    {        return _QTail->_data;    }private:    Node<T>* _QHead;    Node<T>* _QTail;    size_t _size;};

main.cpp

#include"queue.h"template<class T>class Stack{public:    Queue<T>* EmptyQ = &_p1; //指向空队列的指针    Queue<T>* NonEmptyQ = &_p2;  //指向非空队列的指针    void Swap()    {        if (!EmptyQ->Empty())  //如果p1队列不为空,交换两个指针变量的值        {            swap(EmptyQ, NonEmptyQ);        }    }    void Push(const T& x) //哪个队列不是空的就往哪个队列插    {        Swap();        NonEmptyQ->Push(x);        _size++;    }    void Pop()    {        Swap();        size_t size = _size;        while (size > 1) //把前_size - 1个数,挪到另外一个队列        {            T tmp = NonEmptyQ->Fornt();            EmptyQ->Push(tmp);            NonEmptyQ->Pop();            size--;        }        NonEmptyQ->Pop(); //删除最后一个元素        _size--;    }    bool Empty()    {        return _size == 0;    }    int Size()    {        return _size;    }    const T& Top()    {        Swap();        return NonEmptyQ->Back();    }private:    Queue<T> _p1;    Queue<T> _p2;    size_t _size;};void Test(){    Stack<int> s1;    s1.Push(1);    s1.Push(2);    s1.Push(3);    s1.Pop();    s1.Push(4);    s1.Top();    s1.Pop();    s1.Pop();    s1.Pop();}int main(){    Test();    getchar();    return 0;}
0 0