栈与队列

1.用2个栈实现一个队列(剑指offer——面试题7)

思想:往队尾添加结点的时候,就是把当前结点压入stack1中。删除队首的结点时,首先判断stack2是否为空,如果stack2为空,则把stack1中的所有结点都压入到stack2中。如果stack2仍然为空,说明队列为空。删除stack2中的栈顶结点。

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

//用2个栈实现队列
template<typename T>
class CQueue{
public:
    CQueue(void);
    ~CQueue(void);
    void appendTail(const T& node);
    T deleteHead();
private:
    stack<T> stack1;
    stack<T> stack2;
};

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

template<typename T> T CQueue<T>::deleteHead()
{
    if(stack2.size()<=0)
    {
        while(stack1.size()>0)
        {
            T & data=stack1.top();
            stack1.pop();
            stack2.push(data);
        }
    }
    if(stack2.size()==0)
        throw new exception("queue is empty");
    T head=stack2.top();
    stack2.pop();
    return head;
}

2.用2个队列实现一个栈

思想:第一个结点可以随意往任意空栈中添加。接下来往栈中添加结点的时候就是把结点压入非空的那个栈的末尾。删除结点时,依次删除非空队列中的结点,并且压入到另一个队列中,直到当前队列剩下最后一个结点,将其删除。

原文地址:https://www.cnblogs.com/wy1290939507/p/4678871.html