kyds 栈的基本功能

//第三章 栈的基本功能实现
//

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
#define ElemType int
#define MaxSize 50


// 函数声明区域
typedef struct{
    ElemType data[MaxSize];
    int top;
}Sqstack;

void InitStack(Sqstack *S);
bool IfEmpty(Sqstack *S);
bool Push(Sqstack *S,ElemType x);
bool Pop(Sqstack *S,ElemType *x);
bool GetTop(Sqstack *S, ElemType *x);
int SizeofStack(Sqstack *S);
bool tian(Sqstack *S, int n, int fanwei);
void printstack(Sqstack *S);

int main() {
    time_t t;
    srand((unsigned) time(&t)); // 初始化随机种子
    printf("开始了
");
/////////////////////////////////////////////////////////////////////////////////////////////////////
    Sqstack *S;
    S = (Sqstack *)malloc(sizeof(Sqstack));
    InitStack(S);
    tian(S,10,100);
    printstack(S);
    printf("
结束了
");
    return 0;
}



void InitStack(Sqstack *S){
    S->top = -1;
}

//判空,若空,返回
bool IfEmpty(Sqstack *S){
    if (S->top == -1)
        return false;
    return true;
}


// 进栈,将x装入栈S
bool Push(Sqstack *S,ElemType x){
    if (S->top == MaxSize){
        printf("
栈满了,将 %d 装入失败。
",x);
        return false;
    }
    S->data[++S->top] = x;
    return true;
}

// 出栈,返回出栈的那个值
bool Pop(Sqstack *S,ElemType *x){
    if (S->top == -1){
        printf("
出栈失败,栈为空栈,将返回false
");
        return false;
    }
    *x = S->data[S->top--];
    return true;
}


// 读栈顶
bool GetTop(Sqstack *S, ElemType *x){
    if (S->top == -1){
        printf("
读取栈顶失败,栈为空栈.
");
        return false;
    }
    *x = S->data[S->top];
    return true;
}


// 栈的大小,返回一个int
int SizeofStack(Sqstack *S){
    return (S->top)+1;
}


// 给栈装入n个数,范围是0-fanwei
bool tian(Sqstack *S, int n,int fanwei){
    if (SizeofStack(S)+n >MaxSize)
        return false;
    for (int i=0; i < n ; i++){
        Push(S,rand()%fanwei);
    }
    return true;
}


// 打印栈的每一个数,从栈顶开始
void printstack(Sqstack *S){
    printf("这个栈为:栈顶");
    int i = S->top;
    while (i != -1){
        printf("%d -",S->data[i]);
        i--;
    }
    printf("栈底
");
}
原文地址:https://www.cnblogs.com/gallien/p/13752775.html