- 栈是一种先进后出的结构,队列是先进先出结构
- 下面模拟两个栈实现一个队列的过程
先将a,b,c三个元素压入stack1中,此时stack2为空
进行堆头删除操作,a先进去的需要将a先删除,由于a在栈底,所以我们将stack1中的元素全部出栈到stack2中,然后再将stack2中的栈顶元素出栈。
继续删除队头元素,stack2不为空,因此继续从stack2中出栈
插入元素d,直接将元素插入stack1中
继续删除队头元素,由于stack2不为空,继续从stack2中出栈。
继续删除元素d,由于stack2为空,因此将stack1中的元素出栈,然后再入栈到stack2中,再从stack2中弹出栈顶元素。
思路有了,上代码:
写法一:不带模板
class CQueue
{
stack<int> st1, st2;
public:
CQueue()
{
while (!st1.empty())
{
st1.pop();
}
while (!st2.empty())
{
st2.pop();
}
}
void appendTail(int value)
{
st1.push(value);
}
int deleteHead()
{
if (st2.empty())
{
while (!st1.empty())
{
int val = st1.top();
st1.pop();
st2.push(val);
}
}
if (st2.empty())
{
return -1;
}
int val = st2.top();
st2.pop();
return val;
}
};
写法二:带模板(在面试的时候这种写法更好一点)
template <typename T>
class CQueue
{
stack<T> st1, st2;
public:
CQueue();
void appendTail(const T& value);
T deleteHead();
};
template <typename T>
CQueue<T>::CQueue()
{
while (!st1.empty())
{
st1.pop();
}
while (!st2.empty())
{
st2.pop();
}
}
template <typename T>
void CQueue<T>::appendTail(const T& value)
{
st1.push(value);
}
template <typename T>
T CQueue<T>::deleteHead()
{
if (st2.empty())
{
while (!st1.empty())
{
T val = st1.top();
st1.pop();
st2.push(val);
}
}
if (st2.empty())
{
throw new exception("que is empty");
}
T head = st2.top();
st2.pop();
return head;
}