顺序栈

顺序栈:

#include <iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
typedef char Element;
#define maxsize 10
// 顺序栈
typedef struct {
    Element c[maxsize];
    int top;  // 栈顶指针

}Sqstack;

//初始化栈
void initStack(Sqstack &s){
    s.top=-1;
}
//判断是否为空
bool SqstackEmpty(Sqstack s){
    if(s.top==-1)
        return true;
    else
        return false;
}

//进栈
bool pushStack(Sqstack &s,Element c){
        if(s.top==maxsize-1){
            return false;
        }
        s.c[++s.top]=c;
        //printf("top:%d",s.top);
        return true;
}

//出栈
bool popStack(Sqstack &s){
    if(s.top==-1){
        //printf("栈为空!");
        cout<<"栈为空"<<endl;
        return false;
    }
    s.top=s.top-1;
    return true;
}

//遍历栈
void getStack(Sqstack s){
    int i=0;
    for(i;i<=s.top;i++){
        printf("%c ",s.c[i]);
    }

}
int main()
{
    Sqstack s;
    initStack(s); //初始化栈
    int a=pushStack(s,'A');
        a=pushStack(s,'B');
        a=pushStack(s,'C');
        a=pushStack(s,'D');
        a=pushStack(s,'E');
        getStack(s);

    printf("\n");
    if(!SqstackEmpty(s)){  //若栈不为空
        int b =popStack(s); //出栈
        getStack(s);   //遍历
    }

}

 

posted @ 2022-04-20 21:37  葛优猿  阅读(19)  评论(0)    收藏  举报