栈的顺序存储结构及实现

来源:互联网 发布:sql 带游标的存储过程 编辑:程序博客网 时间:2024/04/30 17:48
/*栈的顺序存储结构及实现*/

//顺序栈的存储结构定义

const int StackSize = 10;        //栈元素最多10个
typedef int DataType;        //DataType为栈元素的数据类型
typedef struct
{
    DataType data[StackSize];        //存放栈元素的数组
    int top;                    //栈顶指针,为栈元素在数组中的下标
}SeqStack;


//栈的初始化算法
void InitStack(SeqStack &S)
{
    S.top = -1;
}

//入栈操作

void Push(SeqStack &S,DataType x)
{
    if(S.top == StackSize - 1)
    {
        printf("上溢");
        exit(-1);
    }
    S.data[++S.top] = x;
}

//出栈操作

DataType Pop(SeqStack &S)
{
    if(S.top == -1)
    {
        printf("下溢");
        exit(-1);
    }
    x = S.data[S.top--];
    return x;
}

//取栈顶元素

DataType GetTop(SeqStack &S)
{
    if(S.top == -)
    {
        printf("下溢");exit(-1);
    }
    return S.data[S.top];
}

//判空操作

int Empty(SeqStack &S)
{
    if(S.top == -1)
        return 1;            //空栈返回1
    else
        return0;
}