C++数据结构 ---- 顺序栈

环境配置

codeblocks

windows10

项目结构

代码

SqStackClass.h

#ifndef _SQSTACKCLASS_H_
#define _SQSTACKCLASS_H_

#include <iostream>

template <typename T>
class SqStackClass
{
public:
	static const int MAXSIZE;
	SqStackClass(void);
	~SqStackClass(void);
	bool StackEmpty(void) const;
	bool StackFull(void) const;
	bool Push(const T &e);
	bool Pop(T &e);
	bool GetTop(T &e) const;
protected:
private:
	T *data;
	int top;
};

template <typename T>
const int SqStackClass<T>::MAXSIZE = 100;

template <typename T>
SqStackClass<T>::SqStackClass(void)
{
	data = new T[MAXSIZE];
	top = 0;
}

template <typename T>
SqStackClass<T>::~SqStackClass(void)
{
	delete []data;
}

template <typename T>
bool SqStackClass<T>::StackEmpty(void) const
{
	return (0 == top);
}

template <typename T>
bool SqStackClass<T>::StackFull(void) const
{
	return (MAXSIZE == top);
}

template <typename T>
bool SqStackClass<T>::Push(const T &e)
{
	if (StackFull())
	{
		return false;
	}

	data[top++] = e;
	return true;
}

template <typename T>
bool SqStackClass<T>::Pop(T &e)
{
	if (StackEmpty())
	{
		return false;
	}

	e = data[--top];
	return true;
}

template <typename T>
bool SqStackClass<T>::GetTop(T &e) const
{
	if (StackEmpty())
	{
		return false;
	}

	e = data[top - 1];
	return true;
}

#endif // _SQSTACKCLASS_H_

main.cpp

#include <iostream>
#include "SqStackClass.h"

using namespace std;

int main(void)
{
	SqStackClass<int> S1;
	SqStackClass<int> S2;
	const int n = 10;
	int a[n] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
	int e;

	for (int i = 0; i < n; ++i)
	{
		S1.Push(a[i]);
	}

	S1.GetTop(e);
	cout << "S1.top = " << e << endl;

	cout << "S1: " << endl;

	while (!S1.StackEmpty())
	{
		S1.Pop(e);
		cout << e << " ";
		S2.Push(e);
	}

	cout << endl;

	S2.GetTop(e);
	cout << "S2.top = " << e << endl;

	cout << "S2: " << endl;

	while (!S2.StackEmpty())
	{
		S2.Pop(e);
		cout << e << " ";
	}

	cout << endl;

	system("PAUSE");
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值