数据结构-栈模拟队列练习

设计利用两个栈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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值