C++之顺序栈

#include <iostream>
using namespace std;
template<class T>
//顺序栈类
class LinearStack
{
public:
	LinearStack(int LSMaxSize); //构造函数,创建空栈
	~LinearStack();//析构函数,删除栈
	bool IsEmpty();// 栈空返回true,非空返回false
	bool IsFull();//栈满返回true,不满返回false
	//int GetElementNumber();//求栈中元素的个数
	bool Push(const T& x);//在栈顶插入元素x,成功返回truc,失败返回false
	bool Top(T& x);//求栈顶元素的值放入x中,成功返回true,失败返回false
	bool Pop(T& x);//从栈顶册除一个元素,并将该元素的值放入x中
	void OutPut(ostream& out)const;//将顺序栈放到输出流out中输出
private:
	int top;// 用来表示栈顶
	int MaxSize;// 栈中最大元素个数
	T* element;//一维动态数组
};

//实现构造函数
template<class T>
LinearStack<T>::LinearStack(int LSMaxSize)
{
	MaxSize = LSMaxSize;
	element = new T[LSMaxSize];
	top = -1;
}
//实现析构函数
template<class T>
LinearStack<T>::~LinearStack()
{
	delete []element;
}
//实现判断栈是否为空
template<class T>
bool LinearStack<T>::IsEmpty()
{
	return top == -1;

}
//实现判断栈是否为满
template<class T>
bool LinearStack<T>::IsFull()
{
	return top + 1 == MaxSize;
}
/*
template<class T>
int LinearStack<T>::GetElementNumber()
{
	int n;
	if (IsFull())
		return MaxSize;
	else if (IsEmpty())
		return 0;
	else {

	}
}
*/
template<class T>
bool LinearStack<T>::Push(const T& x)
{
	if (IsFull())
		return false;
	else {
		top++;
		element[top] = x;
		return true;
	}
}
//实现求栈顶元素
template<class T>
bool LinearStack<T>::Top(T& x)
{
	if (IsEmpty)
		return false;
	else
	{
		x = element[top];
		return true;
	}
}
//实现出栈
template<class T>
bool LinearStack<T>::Pop(T& x)
{
	if (IsEmpty())
		return false;
	else
	{
		x = element[top];
		top--;
		return true;
	}
}
//实现顺序栈的输出,栈底到栈顶的顺序输出的。
template<class T>
void LinearStack<T>::OutPut(ostream& out) const
{
	for (int i = 0; i <= top; i++)
		out << element[i] << endl;
}
//重载插入运算符<<
template<class T>
ostream& operator<<(ostream& out, const LinearStack<T>& x)
{
	x.OutPut(out);
	return out;
}

void conversion(int n, int base) {
	int x, y;
	y = n;
	LinearStack<int> s(100);
	while (y) {
		s.Push(y % base);
		y = y / base;
	}
	cout << "十进制数" << n << "转换为" << base << "进制为:\n";
	while (!s.IsEmpty()) {
		s.Pop(x);
		cout << x;
	}
}
int main() {
	LinearStack<int> s(10);
	int n, base;
	cout << "请输入十进制数和要转换的进制基数:" << endl;
	cin >> n >> base;
	conversion(n, base);
	cout << endl;

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值