(转载)顺序栈c++实现

(转载)http://myswirl.blog.163.com/blog/static/51318642200882310239324/

SqStack.h
****************************************
#include <iostream>
using std::cout;
using std::endl;

template <class T>
class SqStack{
    public:
        SqStack(int init=50, int incr=10);
        bool StackEmpty() const;//判断栈是否为空
        T *GetTop() const;//得到栈顶指针
        void StackTraverse() const;
        
        bool Push(T &s);//入栈
        bool Pop(T &p);//出栈
        
        ~SqStack();
    private:
        int size; //允许的最大存储空间以元素为单位
        int increaseSize;//递增大小
        T *base; //存储空间基址
        int top; //栈顶指针,栈元素个数 
};
//构造函数
template <class T>
SqStack<T>::SqStack(int init, int incr){
    size = init; //初始大小
    base = new T[size];
    if(!base)exit(1);//存储分配失败
    increaseSize = incr; //顺序表递增大小
    top = 0;   //空栈中元素个数为0
}

template <class T>
bool SqStack<T>::StackEmpty() const{
    return top == 0;
}
//返回栈顶指针
template <class T>
T *SqStack<T>::GetTop() const{
    if( top == 0 )return NULL;//空栈
    return base+top-1;
}
template <class T>
void SqStack<T>::StackTraverse() const{
    if( top == 0 ){
        cout<<"遍历为空栈"<<endl;
    }else{
        //栈底到栈顶输出
        cout<<"栈底到栈顶: ";
        for(int i=0; i<top; i++){
            cout << *(base+i) << " ";
        }
        cout<<endl;
    }
}
//入栈
template <class T>
bool SqStack<T>::Push(T &s){
    if(top == size)return false; //栈已满,无法进行插入
    *(base + top) = s;//插入新的元素
    ++top;
    return true;
}
//出栈,返回删除元素的指针
template <class T>
bool SqStack<T>::Pop(T &p){
    if( top == 0 )return false;//空栈
    p = *(base+top-1);
    --top;
    return true;
}
//析构函数
template <class T>
SqStack<T>::~SqStack(){
    cout << "调用析构函数" << endl;
    delete base;
    base = NULL;
}
*****************************************

main.cc
**********************************************

#include "SqStack.h"

int main()
{
    SqStack<int> *s = new SqStack<int>;
    
    int a = 0;
    int b = 1;
    int c = 2;
    
    if(s->Push(a)){
        cout << "入栈成功!a"<<endl;
    }
    if(s->Push(b)){
        cout << "入栈成功!b"<<endl;
    }
    
    if( s->GetTop() != NULL ){
        cout << "栈顶元素: " << *(s->GetTop()) << endl;    
    }else{
        cout << "空栈了" <<endl;
    }
    
    s->StackTraverse();
    
    int p;
    if( s->Pop(p)){
        cout << "出栈成功!" << p << endl;
    }else{
        cout << "空栈" << endl;
    }
    
    if( s->GetTop() != NULL ){
        cout << "栈顶元素: " << *(s->GetTop()) << endl;    
    }else{
        cout << "栈顶元素:NULL" <<endl;
    }
    s->StackTraverse();
    return 0;
}

**********************************************

posted @ 2013-09-07 20:55  robotke1  阅读(316)  评论(0)    收藏  举报