您的位置:首页 > 其它

SeqStack(Template<class T>)实现

2017-10-12 14:05 239 查看
顺序表实现模板栈(第二次)

这是发过的一个版本的栈的链接

这次用模板再做了一遍

配有测试过的main函数,可以直接学习使用。

#include <iostream>
using namespace std;

template<class T>
class SeqStack{
public:
SeqStack(int sz = 50);
~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 <= 0){
element = NULL;
} else {
element = new T[sz];
}
maxsize = sz;
top = -1;
}
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 + 1;
}

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 = -1;
}
template<class T>
bool SeqStack<T>::isFull()const{
return top >= maxsize - 1;
}
template<class T>
bool SeqStack<T>::isEmpty()const{
return top == -1;
}

template<class U>
ostream& operator<<(ostream &os, SeqStack<U> s){
os<< "maxsize = "<< s.maxsize<< " top = "<< s.top<< endl;
for (int i = s.top; i >= 0; --i){
os << s.element[i];
if (i != 0)
os << " -> ";
}
return os;
}

int main(){
SeqStack<int> s;
for (int i = 0; i < 20; ++i)
s.push(i* 12 - 1);
cout << s<< endl;
for (int i = 0; i < 10; ++i)
s.pop();
cout << s<< endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: