容器的数据结构都是用模板类实现的,包括栈(stack),队列(queue),双端队列(deque),向量(vector)等,下面是栈的模板类,以及成员函数的实现

定义头文件

#include<assert.h>
#include<iostream>
using namespace std;

const int stackIncreament=20;
template<class T>
class SeqStack{
public:
	SeqStack(int sz = 50);
	~SeqStack();
	bool push(const T& x);
	bool pop(const T& x);
	bool isFull()const{return (top == maxsize-1)?true:false;}
	bool isEmpty()const{return (top ==-1)?true:false;}
	int getsize(){return top+1;}
	T gettop();
	void makeEmpty(){top = -1;}
private:
	T * element;
	int maxsize;
	int top;
	void overflowProcess();
};

成员函数的实现

#include "stack.h"

template<class T>
SeqStack<T>::SeqStack(int sz):top(-1),maxsize(sz){
	element = new T[maxsize];
	assert(element!=NULL);
}
template<class T>
bool SeqStack<T>::push(const T& x){
	if(isFull()==true)return false;
	element[++top]=x;
	return true;
}
template<class T>
bool SeqStack<T>::pop(const T& x){
	if(isEmpty()==true)return false;
	x = element[top--];
	return true;
}
template<class T>
T SeqStack<T>::gettop(){
	if(isEmpty()==true)return -1;
	T x = element[top];
	return x;
}
template<class T>
void SeqStack<T>::overflowProcess(){
	T* newarray = new T[maxsize+stackIncreament];
	if(newarray==NULL){
		cerr<<"allocate failed"<<endl;
		exit(1);
	}
	for(int i=0;i<=top;i++){
		newarray[i]=element[i];
	}
	maxsize = maxsize + stackIncreament;
	delete []element;
	element = newarray;
}


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐