栈(stacks)数组实现

堆栈(Stack)栈是允许在一端进行插入和删除操作的特殊线性表。允许进行插入和删除操作的一端称为栈顶(top),另一端为栈底(bottom);栈底固定,而栈顶浮动;栈中元素个数为零时称为空栈。栈结构也称为后进先出表(LIFO)。  

其使用数组实现方式:

实现平台:widows 7 vs2010

FixedCapacityStack.h文件

#pragma once
template<class T>
class FixedCapacityStack
{
private:
	T *data;//数据
	int capacity;//栈的大小
	int top;//栈顶的位置
public:
	FixedCapacityStack(int capacity);
	~FixedCapacityStack(void);
	 bool isEmpty();
	 void push(T item);//入栈
	 T pop();//出栈
	
};
FixedCapacityStack. cpp文件

#include "StdAfx.h"
#include "FixedCapacityStack.h"

template<class T>
FixedCapacityStack<T>::FixedCapacityStack(int capacity)
{
	 data=new T[capacity];
	 top=0;
	 this->capacity=capacity;

}
template<class T>
FixedCapacityStack<T>::~FixedCapacityStack(void)
{
	 delete [] data;
}
template<class T>
void FixedCapacityStack<T>::push(T item)
{
	if(top>=capacity)
	{
		throw "stack overflow";
	}
	else
	{
		data[top++]=item;
	}

}
template<class T>
T FixedCapacityStack<T>::pop()
{
	if(0==top)
	{
		throw "stack is clear";
	}
	else
	{
		return data[--top];
	}
}
template<class T>
bool FixedCapacityStack<T>::isEmpty()
{
	return top==0;
}

测试主函数:

#include "stdafx.h"
#include"FixedCapacityStack.cpp"
#include<iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	FixedCapacityStack<int> ss(10);
	try
	{
	ss.push(1);
	ss.push(2);
	cout<<ss.pop()<<endl;
	cout<<ss.pop()<<endl;
	}
	catch(const char *ex)
	{
		cout<<ex<<endl;
	}
	system("pause");
	return 0;
}
这里 #include"FixedCapacityStack.cpp"  文件 ,如果要是只FixedCapacityStack.h文件 的话,在实例化模板的时候会报链接错误。

测试结果


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值