顺序表实现模板栈(第二次)
这是发过的一个版本的栈的链接
这次用模板再做了一遍
配有测试过的main函数,可以直接学习使用。
#include <iostream>
using namespace std;
template<class T>
class SeqStack{
public:
SeqStack(int sz = );
~SeqStack(){ delete[]element; };
bool push(const T& x);
bool pop();
bool getTop(T& x)const;
bool isEmpty()const;
bool isFull()const;
int getSize()const;
void makeEmpty();
template<class U>
friend ostream& operator<<(ostream& os, SeqStack<U> s);
private:
T* element;
int maxsize, top;
};
template<class T>
SeqStack<T>::SeqStack(int sz) {
if (sz <= ){
element = NULL;
} else {
element = new T[sz];
}
maxsize = sz;
top = -;
}
template<class T>
bool SeqStack<T>::push(const T& x){
if (isFull()){
return false;
} else {
element[++top] = x;
return true;
}
}
template<class T>
int SeqStack<T>::getSize()const {
return top + ;
}
template<class T>
bool SeqStack<T>::pop(){
if (isEmpty()){
return false;
} else{
top--;
return true;
}
}
template<class T>
bool SeqStack<T>::getTop(T& x)const{
if (isEmpty()){
return false;
} else {
x = element[top];
return true;
}
}
template<class T>
void SeqStack<T>::makeEmpty(){
top = -;
}
template<class T>
bool SeqStack<T>::isFull()const{
return top >= maxsize - ;
}
template<class T>
bool SeqStack<T>::isEmpty()const{
return top == -;
}
template<class U>
ostream& operator<<(ostream &os, SeqStack<U> s){
os<< "maxsize = "<< s.maxsize<< " top = "<< s.top<< endl;
for (int i = s.top; i >= ; --i){
os << s.element[i];
if (i != )
os << " -> ";
}
return os;
}
int main(){
SeqStack<int> s;
for (int i = ; i < ; ++i)
s.push(i* - );
cout << s<< endl;
for (int i = ; i < ; ++i)
s.pop();
cout << s<< endl;
}