数据结构(3):顺序栈的表示和实现

/*  语言:C++                  编译环境:Visual C++6.0
                    顺序栈的表示和实现
*/
#include <iostream>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 100
// Status是函数返回值类型,其值是函数结果状态代码
typedef int Status;
// 自定义数据类型别名
typedef int ElemType;
using namespace std;

// 顺序栈的存储结构
typedef struct
{
    ElemType *base; // 栈底指针
    ElemType *top;  // 栈顶指针
    int stacksize;  // 栈可用的最大容量
}SqStack;

// 栈的初始化
Status InitStack(SqStack &S)
{   // 构造一个空栈
    // 为顺序栈动态分配一个最大容量为MAXSIZE的数组空间
    S.base = new ElemType[MAXSIZE]; 
    if(!S.base) exit(OVERFLOW);     // 存储分配失败
    S.top = S.base;                 // top初始为base,空栈
    S.stacksize = MAXSIZE;      // stacksize置为栈的最大容量MAXSIZE
    return OK;
}

// 顺序栈的入栈
Status Push(SqStack &S, ElemType e)
{   // 插入元素e为新的栈顶元素
    // 栈满(S.top的地址值与S.base的地址值之差为顺序栈的长度)
    if(S.top-S.base == MAXSIZE) return ERROR;   
    *S.top++ = e;                   // 元素e压入栈顶,栈顶指针加1
    return OK;
}

// 顺序栈的出栈
Status Pop(SqStack &S, ElemType &e)
{   // 删除S的栈顶元素,用e返回其值
    if(S.top == S.base) return ERROR;   // 栈空
    e = *--S.top;                   // 栈顶指针减1,将栈顶元素赋给e
    return OK;
}

// 取顺序栈的栈顶元素
ElemType GetTop(SqStack S)
{   // 返回S的栈顶元素,不修改栈顶指针
    if(S.top != S.base)     // 栈非空
        return *(S.top-1);  // 返回栈顶元素的值,栈顶指针不变
    return ERROR;
}

int main()
{
    SqStack S;
    // 列表菜单
    cout<<"1 InitStack"<<endl;
    cout<<"2 Push"<<endl;
    cout<<"3 Pop"<<endl;
    cout<<"4 GetTop"<<endl;

    int choice,e;
    while(1)
    {
        cout<<"Input a choice: ";
        cin>>choice;

        // 选择
        switch(choice)
        {
            case 1:
                InitStack(S);
                continue;
            case 2:
                Push(S,3);
                continue;
            case 3:
                Pop(S,e);
                continue;
            case 4:
                cout<<"Get: "<<GetTop(S)<<endl;
                continue;
            default:
                cout<<"End..."<<endl;
                break;
        }
        break;
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值