数据结构-顺序栈(进栈 出栈)

时间:2019-06-28 20:50:56   收藏:0   阅读:93
#include<stdio.h>
#define MaxSize 10

typedef struct SqStack{
    int data[MaxSize];
    int top ;
}SqStack;

//初始化顺序栈
void initStack(SqStack &S){
    S.top = -1; 
} 

//判断栈是否为空   /*栈理论上不存在为满的情况,取决于内存大小*/
int isEmpty(SqStack S){
    if(S.top == -1){//top为1表示为空 
        return 1;
    }else{
        return 0;
    } 
} 

//进栈操作
int push(SqStack &S,int e){
    //进栈要判满
    if(S.top == MaxSize-1){
        return 0;
    } 
    //先移动指针在进行复制 
    ++(S.top);      
    S.data[S.top] = e;
    return 1;
}

//出栈操作
int pop(SqStack &S,int &e){
    //出栈要判空
    if(S.top == -1){
        return 0;
    } 
    //先进行赋值在移动指针 
    e = S.data[S.top];
    --(S.top);
    return 1;
}

//展示栈中的元素
void show(SqStack &S){
    int e;
    while(S.top>-1){
        pop(S,e);
        printf("%d    ",e);
    }
} 
//持续往栈中存放元素
void put(SqStack &S){
    initStack(S);  ///一定要初始化 
    int e;
    scanf("%d",&e);
    while(S.top<MaxSize&&e!=-1){
        push(S,e);
        printf("%d    ===\n ",S.top);
//        printf("输入成功\n");
        scanf("%d",&e);
    }
} 
int main(){
    SqStack S;
    put(S);
    show(S);
    return 0;
} 
 

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!