堆栈(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文件 的话,在实例化模板的时候会报链接错误。
测试结果