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

【数据结构上机练习】3.栈的简单操作

2012-10-29 21:27 501 查看
//第二次上机第一题,栈的简单操作

1 //============================================================================
// Name        : 上机2.1.cpp
// Author      : menglei
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
using namespace std;

template<class T>
class mStack{     //call a stack
private:
int size;
T *stackArray;
int top;
public:
mStack(){
size = 100;
top = -1;
stackArray = new T[100];
}
T pop(){
if(top==-1){
cout<<"stack is empty ,can't pop!"<<endl;
return NULL; //返回NULL会有问题,但编译能通过
}
top--;
return stackArray[top];
}
int push(T value){
if(top==size){
cout<<"stack is full ! can't push !"<<endl;
return -1;
}
stackArray[top++]= value;
return 1;
}
T getTop(void){
if(top==-1){
cout<<"stack is empty! "<<endl;
return NULL;
}
return stackArray[top-1];
}
};

int main() {
mStack <char> m;
m.push('c');
cout<<"top element is:"<<m.getTop()<<endl;
m.push('s');
cout<<"top element is:"<<m.getTop()<<endl;
m.push('d');
cout<<"top element is:"<<m.getTop()<<endl;
m.push('n');
cout<<"top element is:"<<m.getTop()<<endl;
m.pop();
cout<<"top element is:"<<m.getTop()<<endl;
return 0;
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: