1. 程式人生 > >順序棧的表示與實現

順序棧的表示與實現

#include<bits/stdc++.h>
using namespace std;
//------------ ADT Stack 的表示與實現---------------
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OK 1
#define ERROR 0
typedef int SElemType;
typedef int Status;
typedef struct
{
    SElemType *base;
    SElemType *top;
    int stacksize;
}SqStack;

Status InitStack(SqStack &S)
{
    S.base = (SElemType*) malloc(STACK_INIT_SIZE * sizeof(SElemType));
    if(!S.base)
        exit(OVERFLOW);
    S.top = S.base;
    S.stacksize = STACK_INIT_SIZE;
    return OK;
}

Status GetTop(SqStack S, SElemType & e)
{
    if(S.top == S.base)
        return ERROR;
    e = *(S.top - 1);
    return OK;
}

Status Push(SqStack &S, SElemType e)
{
    if(S.top- S.base >= S.stacksize)
    {
        S.base = (SElemType*) realloc(S.base, (S.stacksize+STACKINCREMENT)*sizeof(SElemType));
        if(!S.base)
            exit(OVERFLOW);
        S.top = S.base + S.stacksize;
        S.stacksize += STACKINCREMENT;
    }
    *S.top = e;
    S.top++;
    return OK;
}

Status Pop(SqStack &S, SElemType &e)
{
    if(S.top == S.base)
        return ERROR;
    S.top--;
    e = *(S.top);
    return OK;
}

bool Empty(SqStack S)
{
    if(S.base == S.top)
        return true;
    else
        return false;
}

int main()
{
    SqStack S;
    InitStack(S);
    int n;
    cin >> n;
    while(n--)
    {
        int num;
        cin >> num;
        Push(S, num);
    }
    while(!Empty(S))
    {
        int e;
        GetTop(S, e);
        cout << e << endl;
        Pop(S, e);
    }
    return 0;
}