栈—顺序栈(C实现)

 

// Code file created by C Code Develop
//  顺序栈

#include "ccd.h"
#include "stdio.h"
#include "stdlib.h"
#define MaxSize 10
#define OK 1
#define ERROR 0
#define True 1
#define False 0

// 构造了伪bool类型
typedef int bool;

typedef struct SqStack{
    int data[MaxSize];
    int top;  //栈顶指针
} SqStack;
// typedef SqStack ;

int main(int argc, char **argv) 
{
    
    SqStack S; //声明一个顺序栈(分配空间)
    InitStack(&S);
    printf("栈顶指针:%d\n", S.top);
    int i = 99;
    while(i != 0) {
        printf("输入一个整数:(0结束)");
        scanf("%d", &i);
        if (i!= 0) {
            shuchu(
            push(&S, i));  //压栈
        }}
    view(S);   //辅助函数为了查看栈中元素
    // shuchu(StackEmpty(S));    
    int x = 0;
    
    Getytop(S, &x);    // 读栈顶元素
    view(S);
    //pop(&S, &x);  // 出栈一个元素
    printf("出栈的元素是:%d\n", x);
    view(S);
    
    
    printf("执行完毕");
    
    return 0;
}

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

bool StackEmpty(SqStack S) {
    if(S.top ==  - 1) 
    return True; // 栈空
    else 
    return False; // 非空
}

bool push(SqStack *S, int x) {
    if(S -> top == MaxSize - 1) 
    return False;
    // S -> top = S -> top + 1;    //指针加一
    //  S->data[S->top] = x;        // 新元素入栈
    S -> data[++S -> top] = x; //等价前两行
    printf("栈顶指针是:%d\n", S -> top);
    return OK;
}

bool pop(SqStack *S, int *x) {
    // 出栈    
    if(S -> top ==  - 1) 
    return false;
    else printf("OK");
    //printf("第%d个元素是:%d\n", i++, S.data[S.top]);
    //int z;
    // z = S -> top--;
    //x = (S -> data[2]);
    // x = S -> data[S -> top--];
    // S -> top--;
    return True;    
}
bool Getytop(SqStack S, int *x) {
    // 读栈顶元素
    if(S.top ==  - 1) return False; // 栈空报错;
    printf("栈顶元素是:%d\n", S.data[S.top]);
    S.data[S.top];   
    return True;
}


void view(SqStack S) {
    // 此函数仅仅是为了显示栈中的元素,实际操作不允许,为非法操作
    printf("此时栈中的元素是:\n");
    for(int i = 0; S.top > - 1; S.top--) {
        // 从栈顶依次查看栈中元素
        printf("第%d个元素是:%d\n", i++, S.data[S.top]);
    } 
    // printf("111111111111");
    
}
void shuchu(bool a) {
    if (a) {
        printf("操作成功"); }
    else {
        printf("操作失败FALSE"); }
}

 

posted @ 2021-09-26 21:47  def_Class  阅读(71)  评论(0编辑  收藏  举报