2.1 顺序栈

#include <stdio.h>
#include <stdlib.h>
#define MaxSize 50

// 顺序栈同数组,下标是从0开始,第一个元素占据0号位置,栈空为top=-1,栈满是MaxSize-1
// 记住顺序存储的存储结构。注意有top标记和元素数组
// 关键操作:1.判空(S->top=-1),判满(top=MaxSize-1);2.S->data[++S->top]=e
// 一般return的原则:先return 0再return 1. 判空的return 空则return 1 满则return 0
// 口诀:判空就是空为1 return 1

typedef struct{
    int data[MaxSize];            // 顺序栈,是个数组
    int top;
}SqStack;

//初始化
void InitStack(SqStack *S){
    S->top=-1;
}

int StackEmpty(SqStack *S){
    if(S->top==-1) return 1;      // 确实是空栈
    else
    return 0;
}

//进栈
int Push(SqStack *S,int e){
    if(S->top==MaxSize-1) return 0;
        S->data[++S->top]=e;      // 注意顺序,要是先加再执行
    return 1;
}
// 出栈
int Pop(SqStack *S,int *e){
    if(StackEmpty(S))             // 空是返回的-1错误信息,非空才执行下面
        return 0;
    else
        *e=S->data[S->top--];
    return 1;
}

// 读取栈顶元素,同Pop只是不改变top的计数
int GetTop(SqStack *S,int *e){
    if(StackEmpty(S))             // 空是返回的-1错误信息,非空才执行下面
        return 0;
    else
        *e=S->data[S->top];
    return 1;
}

int main(){
    int e1,e2,e3;
    SqStack S;
    InitStack(&S);

    Push(&S,1);
    Push(&S,2);
    Push(&S,3);
    Push(&S,4);
    Push(&S,5);
    
    Pop(&S,&e1);        printf("Pop:%d\n",e1);
    GetTop(&S,&e2);     printf("GetTop:%d\n",e2);
}

 

posted @ 2019-05-03 20:28  aascn  阅读(147)  评论(0编辑  收藏  举报