顺序栈的定义及相关操作

来源:互联网 发布:网络主播行业分析 编辑:程序博客网 时间:2024/05/21 09:18
#include <stdio.h>#define M 1000typedef char ElemType;typedef struct   //定义一个顺序栈{    ElemType data[M];//栈中最多可放M个元素    int top;//用来存放栈顶元素的下标,top为-1表示栈空} SeqStack;void InitStack(SeqStack *s)//创建一个栈{    s->top=-1;}bool Push(SeqStack *s, char x)//进栈操作{    if(s->top==M-1)        return false;    else    {        s->top++;        s->data[s->top]=x;        return true;    }}bool Pop(SeqStack *s,char *x)  //出栈操作{    if(s->top==-1)        return false;    else    {        *x=s->data[s->top];        s->top--;        return true;    }}bool GetTop(SeqStack *s,char *x)   //取栈顶元素{    if(s->top==-1)        return false;    else    {        *x=s->data[s->top];        return true;    }}bool IsEmpty(SeqStack *s)  //判断栈空{    if(s->top==-1)        return true;    else        return false;}int Size(SeqStack *s)//返回栈中元素的个数{    return s->top+1;}int main(void){    SeqStack Seq;    SeqStack *s=&Seq;    ElemType a;    ElemType *e=&a;    InitStack(s);    printf("栈%s\n",(IsEmpty(s)==true?"空":"不空"));    printf("a进栈\n");    Push(s,'a');    printf("b进栈\n");    Push(s,'b');    printf("c进栈\n");    Push(s,'c');    printf("d进栈\n");    Push(s,'d');    printf("栈%s\n",(IsEmpty(s)==true?"空":"不空"));    GetTop(s,e);    printf("栈顶元素:%c\n",a);    printf("出栈次序:\n");    while(!IsEmpty(s))    {        printf("栈中元素有%d个 ",Size(s));        Pop(s,e);        printf("%c\n",a);    }    printf("\n");    return 0;}