顺序栈表示与实现

//stack basic operation
//sequent list
//if base=top null stack
#include<stdio.h>
#include<iostream.h>
#include<malloc.h>//free
#include<cstdlib>
#include<math.h>
#include<string>
#define MAXSIZE 100
#define OK 1
#define ERROR 0//宏
typedef int Status;
typedef struct
{
    char opera[30];
    int data;
}ElemType;
typedef struct
{
    ElemType *base;//栈底
    ElemType *top;//栈顶
    int stacksize;//栈可用最大容量
}SqStack;
//存储结构over
Status InitStack(SqStack &S)
{
    S.base=(ElemType *)malloc(MAXSIZE*sizeof(ElemType));
    if(!S.base) exit(OVERFLOW);
    S.top=S.base;//初始top指向base
    S.stacksize=MAXSIZE;
    return OK;
}//初始化
Status Push(SqStack &S,ElemType &e)
{//一串连续的地址可以相加减ですか
    if(S.top-S.base==S.stacksize) return ERROR;
    *S.top++=e;//ご注意
    return OK;
}
Status Pop(SqStack &S,ElemType &e)
{
    if(S.top==S.base) return ERROR;
    e=*--S.top;//ご注意
    return OK;
}
ElemType GetTop(SqStack S)
{//返回栈顶元素,不修改栈顶指针
    if(S.base!=S.top) return *(S.top-1);//非空
}
Status EnterData(SqStack &S)
{//for test
    cout<<"かずくれね?"<<endl;
    int length=0;
    cin>>length;
    cout<<"number,opera"<<endl;
    for(int i=0;i<length;i++)
    {
        ElemType e;
        cin>>e.data>>e.opera;
        Push(S,e);
    }
    return OK;
}
void StackTraverse(SqStack S)
{//use GetTop()
    ElemType e;
    int length=0;
    while(S.base!=S.top)
    {
        e=GetTop(S);
        cout<<e.data<<e.opera<<endl;
        --S.top;
        length++;
    }
    cout<<"总计"<<length<<endl;
}
Status DestroyStack(SqStack &S)
{
    free(S.base);//释放malloc(或calloc、realloc)函数给指针变量分配的内存空间的函数
    S.base = NULL;//使用后该指针变量一定要重新指向NULL,防止野指针出现,规避误操作。
    S.top = NULL;
    S.stacksize = 0;
    return OK;
}
void main()
{
    SqStack S;
    InitStack(S);
    EnterData(S);
    cout<<"希望成功录入数据..."<<endl;
    StackTraverse(S);
    cout<<"执行销毁"<<DestroyStack(S)<<endl;
    system("pause");
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值