数据结构-- 出栈入栈

    #include <iostream.h>
    #define STACK_INIT_SIZE 10
    #define NEW_SIZE 10
    using namespace std;
    typedef int ElemType;
    
    typedef struct 
    {
        ElemType *top;
        ElemType *base;
        int stacksize;
    }SpStack;
    
    typedef int Status; 
    Status InitStack(SpStack &s)
    {
        s.base=(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
        if(!s.base) return 0; //初始化不成功 
        s.top=s.base;
        s.stacksize=STACK_INIT_SIZE;
        return 1;
    } 
    
    Status push(SpStack &s,ElemType e)
    {
        //考虑栈满的情况
         if(s.top-s.base>=s.stacksize)
        {
            //增加栈空间 reallc(之前栈的首地址)
            s.base=(ElemType *)realloc(s.base,(s.stacksize+NEW_SIZE)*sizeof(ElemType));
            if(!s.base) return 0;
            s.top=s.base+s.stacksize;
            s.stacksize=s.stacksize+NEW_SIZE;
            
        }
        *s.top++ =e;
        return 1;
    }
    Status pop(SpStack &s,ElemType &e)
    {
        //考虑栈空的情况 
        if(s.top==s.base)
        {
            return 0;
        }
        e=(*--s.top);
        return 1;
    }
    
    bool isStackEmpty(SpStack s)
    {
        if(s.top==s.base)
            return 1;
        return 0;
        
    } 
    int main(int argc, char *argv[])
    {
        SpStack s;
        ElemType a,e;
        InitStack(s);
        cout<<"初始化成功后,入栈"<<endl;
        while(cin>>a)    
        {
            push(s,a);
        }
        
        cout<<"入栈之后,出栈"<<endl; 
        while(!isStackEmpty(s))
        {
            pop(s,e);
            cout<<e<<"   ";
            
        }
    
        system("pause");
        return 0;
    }

参考博文:http://blog.csdn.net/xujinsmile/article/details/7371516

 

posted @ 2016-09-11 22:34  serena45  阅读(227)  评论(0)    收藏  举报