统计栈中的元素个数、正序输出栈里的元素

问题遇到的现象和发生背景

顺序栈相关内容:补充两个功能函数:①count函数统计栈里的元素个数②正序输出栈里的元素

用代码块功能插入代码,请勿粘贴截图

#include
#include
#define MaxSize 100
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];
int top; //栈指针
} SqStack; //声明顺序栈类型
void InitStack(SqStack *&s) //初始化顺序栈
{
s=(SqStack *)malloc(sizeof(SqStack));
s->top=-1;
}
void DestroyStack(SqStack *&s) //销毁顺序栈
{
free(s);
}
bool StackEmpty(SqStack *s) //判断栈空否
{
return(s->top==-1);
}
bool Push(SqStack *&s,ElemType e) //进栈
{
if (s->top==MaxSize-1) //栈满的情况,即栈上溢出
return false;
s->top++;
s->data[s->top]=e;
return true;
}
bool Pop(SqStack *&s,ElemType &e) //出栈
{
if (s->top==-1) //栈为空的情况,即栈下溢出
return false;
e=s->data[s->top];
s->top--;
return true;
}

int main()
{
ElemType e;
SqStack *s;
printf("顺序栈s的基本运算如下:\n");
printf(" (1)初始化栈s\n");
InitStack(s);
printf(" (2)栈为%s\n",(StackEmpty(s)?"空":"非空"));
printf(" (3)依次进栈元素a,b,c,d,e\n");
Push(s,'a');
Push(s,'b');
Push(s,'c');
Push(s,'d');
Push(s,'e');
Display(s);
DestroyStack(s);
return 0;
}

添加这两个函数

int Count(SqStack *s){
    return s->top+1;
}

void Display(SqStack *s){
    for(int i=0; i<=s->top; i++){
        printf("%c ", s->data[i]);
    }
}

完整代码:

#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
typedef char ElemType;
typedef struct
{
    ElemType data[MaxSize];
    int top;                // 栈指针
} SqStack;                  // 声明顺序栈类型

void InitStack(SqStack *&s) // 初始化顺序栈
{
    s = (SqStack *)malloc(sizeof(SqStack));
    s->top = -1;
}
void DestroyStack(SqStack *&s) // 销毁顺序栈
{
    free(s);
}
bool StackEmpty(SqStack *s) // 判断栈空否
{
    return (s->top == -1);
}
bool Push(SqStack *&s, ElemType e) // 进栈
{
    if (s->top == MaxSize - 1) // 栈满的情况,即栈上溢出
        return false;
    s->top++;
    s->data[s->top] = e;
    return true;
}
bool Pop(SqStack *&s, ElemType &e) // 出栈
{
    if (s->top == -1) // 栈为空的情况,即栈下溢出
        return false;
    e = s->data[s->top];
    s->top--;
    return true;
}

int Count(SqStack *s){
    return s->top+1;
}

void Display(SqStack *s){
    for(int i=0; i<=s->top; i++){
        printf("%c ", s->data[i]);
    }
}

int main()
{
    ElemType e;
    SqStack *s;
    printf("顺序栈s的基本运算如下:\n");
    printf(" (1)初始化栈s\n");
    InitStack(s);
    printf(" (2)栈为%s\n", (StackEmpty(s) ? "空" : "非空"));
    printf(" (3)依次进栈元素a,b,c,d,e\n");
    Push(s, 'a');
    Push(s, 'b');
    Push(s, 'c');
    Push(s, 'd');
    Push(s, 'e');
    printf("栈内元素个数:%d\n", Count(s));
    Display(s);
    DestroyStack(s);
    return 0;
}