数据结构——用类模板实现顺序栈(C++)

 用Type代替所有int类型

 不用类模板的代码:

 不用类模板的子函数:

 用类模板的子函数:

 

 使用类模板修改后的栈基本操作代码:

/*main.cpp文件*/
#include "Stack.h"

/*类模板不带异常捕获*/
int main(){
	CharStack s1(2);//定义一一个字符型的堆栈
	DoubleStack s2(2);//在定义一个double型堆栈 
	char ch;
	double d;
	
	s1.push('a');
	s1.push('b');
	ch=s1.pop();
	cout<<ch<<endl;
	ch = s1.pop();
	cout <<ch<<endl;
	
	s2.push(2.1);
	s2.push(3.0);
	d=s2.pop();
	cout <<d <<endl;
	d=s2.pop();
	cout << d <<endl;
	
}
/*Stack.h文件*/
#ifndef STACK_H
#define STACK_H


const int MAX_SIZE=100;
template<class DataType>
class stack
{
privata:
    DataType *data;
    int size;
    int top;
public:
	Stack();
	Stack(int s);//这个是数组长度,i、必须用int 
	~Stack();
	//void push(char ch);
	void push(DataType n);
	//char pop();
	DataType pop();
	//char getTop();
	DataType getTop();
	bool isEmpty();
	bool isFull();
	void setNull();
	void reverseDisplay();
	DataType* getData();
	int getLength();
};
//为保证模板类可以正常使用
//需要在源文件的末尾加上
typedef Stack<char> CharStack;
typedef Stack<int> IntStack;
typedef Stack<double> DoubleStack;

#endif
/*Stack.cpp文件*/
#include "Stack.h"
#include <iostream>
using namespace std;

templata<class DataType>
Stack<DataType>::Stack(){
	top = -1;
	size = MAX_SIZE;
	data = new DataType[size];
}

templata<class DataType>
Stack<DataType>::Stack(int s){
	size = s;
	top = -1;
	data = new DataType[size];
}
templata<class DataType>
Stack<DataType>::~Stack(){}

//以此类推,等等子函数

//在.cpp文件中显示。需要声明 
typedef class Stack<char> ;
typedef class Stack<int> ;
typedef class Stack<double> ; 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值