用两个栈实现队列

栈为先进后出的一种数据结构,队列为先进先出的数据结构。

要用栈来实现队列,显然需要两个栈,一个栈来实现队尾入队,一个栈来实现队首出队。

如何具体实现呢

要分为一下几种情况:

设栈A、B;

1、B中有元素时,直接让B出栈,即可完成队列出队;

2、当A中有元素,B中没有元素时,将A中元素全部出栈到入栈B,即可完成类似倒序这样A最底下的元素就到了B的最上面,随后出栈,完成队首出队操作;

3、A、B都没有元素返回-1;

 

 

栈示意图

队列示意图

class CQueue {
public:
    stack<int> A,B;
    CQueue() {

    }
    
    void appendTail(int value) {
        A.push(value);
    }
    
    int deleteHead() {
        if(!B.empty())
        {
            int tmp=B.top();
            B.pop();
            return tmp;
        }
        if(A.empty()) return -1;
        while(!A.empty())
        {
            int tmp=A.top();
            A.pop();
            B.push(tmp);
        }
        int tmp=B.top();
        B.pop();
        return tmp;
    }
};

 

posted @ 2021-03-25 10:52  平平淡淡yg  阅读(164)  评论(0编辑  收藏  举报