zoukankan      html  css  js  c++  java
  • C++ 堆栈

    #ifndef SEQSTACK_H
    #define SEQSTACK_H
    
    #include<iostream>
    using namespace std;
    
    class SeqStack{
    public:
        SeqStack(int size=defaultMaxsize){
            if(size>0){
                maxSize=size;
                data=new int[maxSize];
                for(int i=0;i<maxSize;++i){
                    data[i]=0;
                }
                top=-1;
            }
        }
        //判断栈空算法
        bool Empty_SeqStack(SeqStack *s);
        //入栈算法
        bool Push_SeqStack(SeqStack *s,int x);
        //出栈算法
        bool Pop_SeqStack(SeqStack *s,int *x);
        //取栈顶元素
        bool Top_SeqStack(SeqStack *s,int *x);
    private:
        //默认长度
        const static int defaultMaxsize=10;
        //最大长度
        int maxSize;
        //堆栈元素
        int *data;
        //栈顶元素位置
        int top;
    };
    
    bool SeqStack::Empty_SeqStack(SeqStack *s){
        if(s->top==-1){
            return true;
        }
        return false;
    }
    
    bool SeqStack::Push_SeqStack(SeqStack *s,int x){
       if(s->top<maxSize-1){
           s->data[++s->top]=x;
           return true;
       }
       return false;
    }
    
    bool SeqStack::Pop_SeqStack(SeqStack *s,int *x){
        if(s->Empty_SeqStack(s)){
            return false;
        }else{
            *x=s->data[s->top--];
            return true;
        }
    }
    
    bool SeqStack::Top_SeqStack(SeqStack *s,int *x){
        if(s->Empty_SeqStack(s)){
            return false;
        }else{
            *x=s->data[s->top];
            return true;
        }
    }
    
    #endif
    #include<iostream>
    #include"SeqStack.h"
    using namespace std;
    
    int main(){
        int data[10]={0,1,2,3,4,5,6,7,8,9},a,b;
        int *t=&a,*p=&b;
        SeqStack *s=new SeqStack();
        for(int i=0;i<=5;++i){
            s->Push_SeqStack(s,i);
        }
        if(s->Empty_SeqStack(s)){
            cout<<"入栈失败"<<endl;
        }else{
            s->Top_SeqStack(s,t);
            cout<<"入栈成功,栈顶元素是:"<<*t<<endl;
        }
        if(s->Pop_SeqStack(s,p)){
             s->Top_SeqStack(s,t);
            cout<<"出栈成功,移除栈顶元素是:"<<*p<<"新的栈顶元素是:"<<*t<<endl;
        }
        return 0;
    }
  • 相关阅读:
    php解决与处理网站高并发 大流量访问的方法
    mysql事务和锁InnoDB
    从一个死锁看mysql innodb的锁机制
    Git如何删除自己创建的项目
    公众号的坑
    字符串转Unicode码
    字符串转UTF-8码(%开头)
    git介绍和使用
    ng2中文文档地址
    两个数组的排序方法
  • 原文地址:https://www.cnblogs.com/arno1394/p/11251299.html
Copyright © 2011-2022 走看看