您的位置:首页 > 理论基础 > 数据结构算法

数据结构学习之数组栈实现

2012-10-26 14:51 573 查看
#ifndef ARRAYSTACK_H
#define ARRAYSTACK_H

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

template <class T> class ArrayStack{
int size;
int top;
T* contain;
public:
ArrayStack():size(0),top(-1),contain(NULL){}
ArrayStack(int MaxSize);
void Push(T& element);
T& GetTop();
T& Pop();
bool IsEmpty();
void MakeEmpty();
int getSize(){return size;};
};

template<class T> ArrayStack<T>::ArrayStack(int MaxSize){
size = MaxSize;
top = -1;
contain = new T[size];
}

template<class T> void ArrayStack<T>::Push(T& element){
assert(top != size-1);
contain[++top] = element;
}

template<class T> T& ArrayStack<T>::Pop(){
assert(top!=-1);
return 	contain[top--];
}

template<class T> T& ArrayStack<T>::GetTop(){
assert(top!=-1);
return 	contain[top];
}

template<class T> void ArrayStack<T>::MakeEmpty(){
top = -1;
}

template<class T> bool ArrayStack<T>::IsEmpty(){
return top==-1;
}
#endif

void show(ArrayStack<int> as){
ArrayStack<int> data(as.getSize());
int temp=0;
while(!as.IsEmpty()){
temp=as.Pop();
cout<<temp<<" ";
data.Push(temp);
}
cout<<endl;

}

void main(){
ArrayStack<int> a(10);
int b=0;
for(int i=0;i<10;i++){
b++;
a.Push(b);
}
show(a);
for(i=0;i<5;i++){
a.Pop();
}
show(a);
cout<<a.IsEmpty()<<endl;
cout<<a.GetTop()<<endl;
a.MakeEmpty();
cout<<a.IsEmpty()<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐