用兩個隊列實現一個棧

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章