主要问题:使用两个堆栈实现队列的插入与删除。
基本思路:设两个堆栈为s1与s2,s1用于存放新插入的元素,队列的尾部;当要删除元素的时候,需要删除队列的头部元素,如果s2中没有元素,那么需要将s1中的元素依次弹出并压入到s2中;如果s2中有元素,那么直接弹出s2头部的元素就是队列尾部的元素。(因为元素入栈s1时,是从前向后,从s1弹出来,压入s2时,从后向前压入,那么从s2依次弹出的就是元素进入s1的顺序。)
代码如下:
//用两个堆栈实现队列的插入与删除(插入尾部,删除头部)
#include <iostream>
#include <stack>
#include <exception>
#include <string>
using namespace std;
class StackQueue
{
//public:
// StackQueue(void);
// ~StackQueue(void);
//
public:
void appendTail(const int i);
int deleteHead();
private:
stack<int> stack1;
stack<int> stack2;
};
void StackQueue::appendTail(const int i)
{
stack1.push(i);
}
int StackQueue::deleteHead()
{
if(stack2.size()<=0)
{
int data;
while(stack1.size()>0)
{
data=stack1.top();
stack1.pop();
stack2.push