算法面试题五

试用多态实现线性表(队列,串,堆栈),要求具备线性表的基本操作(pop,push,测长等)


这里实现其共性模板,代码如下:

#include <iostream>
#include <string.h>
#include <climits>
#include <new>
#include <stdio.h>
#include <io.h>
#include <fcntl.h>
#include <string.h>
#include <iomanip>

template<class T>
class tcontainer{
public:
	virtual void push(T &a)=0;
	virtual void pop(void)=0;
	virtual int size(void)=0;
};

template<class T>
class tvector : public tcontainer<T>{
public:
	static const int step=100;
	tvector(){
		_size = 0;
		_cap = step;
		_buf = 0;
		re_capacity(_cap);
	};
	~tvector(){
		if(_buf)
			free(_buf);
	};
	virtual void re_capacity(int s){
		if(_buf)
			_buf=(T *)realloc(_buf,s*sizeof(T));
		else{
			_buf=(T*)malloc(sizeof(T)*s);
		}
	};
	virtual void push(T &a){
		_size++;
		if(_size>_cap)
			re_capacity(_cap+=step);
		_buf[_size-1] = a;
	}
	virtual void pop(void){
		if(_size)
			_size--;
	}
	virtual int size(void){
		return _size;
	}
	const T &operator[](int index){
		if(index>=0&&index<_size)
			return *(_buf+index);
	} 
private:
	int _cap;
	int _size;
	T* _buf;
};


int main(int argc, char *argv[])
{ 
	tvector<int> v;
	for(int i=0;i<300;++i)
		v.push(i);
    for(int i=1;i<301;++i)
		(i%15==0)?(cout<<v[i-1]<<endl):(cout<<setw(3)<<v[i-1]<<" ");

	getchar();
	return 0;
}
测试结果:



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值