设计利用两个栈sl,s2模拟一个队列,请写出实现入队、出队和判队列空的函数的实现。
栈类
/*Stack.h*/
#pragma once
#ifndef _STACK_H
#define _STACK_H
#include<iostream>
using namespace std;
const int DEFAULT_SIZE = 100;
template <class DataType>
class SqStack {
protected:
DataType* elems;
int maxSize;
int top;
public:
SqStack(int size = DEFAULT_SIZE); //构造函数
virtual ~SqStack(); //析构函数
bool IsEmpty() const; //判断栈是否为空
int Push(const DataType& e); //入栈
void Pop(DataType& e); //出栈
};
#endif
栈的函数实现
/*Stack.cpp*/
#include"Stack.h"
template<class DataType>
SqStack<DataType>::SqStack(int size) {
elems = new DataType[size];
maxSize = size;
top = -1;
}
template<class DataType>
SqStack<DataType>::~SqStack()
{
delete[]elems;
}
template<class DataType>
int SqStack<DataType>::Push(const DataType& e) {
if (top == maxSize - 1)
return 0;
else {
elems[++top] = e;
return 1;
}
}
template<class DataType>
void SqStack<DataType>::Pop(DataType& e) {
if (IsEmpty())
cout << "empty";
else {
e = elems[top--];
}
}
template<class DataType>
bool SqStack<DataType>::IsEmpty() const
{
return top == -1;
}
模拟队列类
/*TwoStackToQueue.h*/
#pragma once
#ifndef _TSTQ_H
#define _TSTQ_H
#include"Stack.cpp"
template<class DataType>
class TwoStackToQueue {
protected:
SqStack<DataType> s1;
SqStack<DataType> s2;
public:
TwoStackToQueue();
bool IsEmpty() const; //判断队列是否为空
int EnQueue(const DataType e);//入队
void DelQueue(DataType& e); //出队
};
#endif
函数实现
/*TwoStackToQueue.cpp*/
#include"TwoStackToQueue.h"
template<class DataType>
TwoStackToQueue<DataType>::TwoStackToQueue() {}
template<class DataType>
int TwoStackToQueue<DataType>::EnQueue(const DataType e)
{
return s1.Push(e);
}
template<class DataType>
void TwoStackToQueue<DataType>::DelQueue(DataType& e)
{
DataType e1;
if (!s1.IsEmpty())
{
while(!s1.IsEmpty())
{
s1.Pop(e1);
s2.Push(e1);
}
s2.Pop(e);
while (!s2.IsEmpty())
{
s2.Pop(e1);
s1.Push(e1);
}
}
}
template<class DataType>
bool TwoStackToQueue<DataType>::IsEmpty() const
{
return s1.IsEmpty();
}