栈的顺序存储及其基本操作

#include <stdio.h>
#include <stdlib.h>
#define M 10

typedef struct   //定义一个顺序栈
{
    char data[M];
    int top;
}SqStack;

void InitStack(SqStack &st)//创建一个栈
{
    st.top=-1;
}

int PushStack(SqStack &st, char x)//进栈操作
{
    if(st.top==M-1)
        return 0;
    else
    {
        st.top++;
        st.data[st.top]=x;
        return 1;
    }
}

int PopStack(SqStack &st,char &x)  //出栈操作
{
    if(st.top==-1)
        return 0;
    else
    {
        x=st.data[st.top];
        st.top--;
        return 1;
    }
}

int GetTop(SqStack st,char &x)   //取栈顶元素
{
    if(st.top==-1)
        return 0;
    else
    {
        x=st.data[st.top];
        return 1;
    }
}

int StackEmpty(SqStack st)  //判断栈空
{
    if(st.top==-1)
        return 1;
    else
        return 0;
}

int main()
{
    SqStack st;
    char e;
    InitStack(st);
    printf("栈%s\n",(StackEmpty(st)==1?"空":"不空"));
    printf("a进栈\n");PushStack(st,'a');
    printf("b进栈\n");PushStack(st,'b');
    printf("c进栈\n");PushStack(st,'c');
    printf("d进栈\n");PushStack(st,'d');
    printf("栈%s",(StackEmpty(st)==1?"空":"不空"));
    GetTop(st,e);
    printf("栈顶元素:%c\n",e);
    printf("出栈次序:");
    while(!StackEmpty(st))
    {
        PopStack(st,e);
        printf("%c ",e);
    }
    printf("\n");
    return 0;
}
输入元素后输出
posted on 2013-08-14 11:13  lie隼  阅读(341)  评论(0编辑  收藏  举报