天天看點

SeqStack(Template<class T>)實作

順序表實作模闆棧(第二次)

這是發過的一個版本的棧的連結

這次用模闆再做了一遍

配有測試過的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;
}