栈的顺序实现

的顺序实现
时间:2006/03/27
测试环境: TC2.0

#include <stdio.h>
#define True 1
#define False 0
#define LEN sizeof(ElemType)
#define Stack_InitSize 100
#define Stack_Increment 30

typedef int ElemType;

struct SqStack
{
    ElemType *base;
    ElemType *top;
    int stacksize;
};

/*构造一个空栈*/
void InitStack(struct SqStack *S)
{
    S->base = (ElemType *)malloc(Stack_InitSize*LEN);
    if(!S->base)
        return;
    S->top = S->base;
    S->stacksize = Stack_InitSize;
    return;
}

/*销毁一个栈*/
void DestroyStack(struct SqStack *S)
{
    while(S->top!=S->base)
        S->top--;
    free(S->base);
    free(S);
}

/*将栈里面的元素清空*/
void ClearStack(struct SqStack *S)
{
    while(S->top!=S->base)
        S->top--;
}

/*判断是否为空栈*/
void IsEmpty(struct SqStack *S)
{
    if(S->top==S->base)
        printf("/nThe SqStack is empty!");
    else
        printf("/nThe SqStack is not empty!");
    return;
}

/*按出栈顺序打印这个栈*/
void Print(struct SqStack *S)
{
    ElemType *p;
    p = S->top;
    while(p!=S->base)
    {
        p--;
        printf("%d ",*p);
    }
    printf("/n");
    p=NULL;
}

/*向栈里压入数据e*/
void Push(struct SqStack *S,ElemType e)
{
    if(S->top - S->base >= S->stacksize) /*栈满,重新分配更大的空间*/
    {
        S->base = (ElemType *)realloc(S->base,(S->stacksize+Stack_Increment)*LEN);
        S->top = S->base + S->stacksize;
        S->stacksize += Stack_Increment;
    }
    *S->top = e;
    S->top++;
    return;
}

/*弹出栈顶元素*/
void Pop(struct SqStack *S)
{
    if(S->top==S->base)
        return;
    S->top--;
    printf("Pop the data:%d/n",*S->top);
    return;
}

/*返回栈顶元素*/
int GetTop(struct SqStack *S)
{
    ElemType *p = S->top;
    if(S->top==S->base)
    {
        printf("The stack is empty!");
        return False;
    }
    return *(--p);
}

void main()
{
    struct SqStack *SS;
    int i;
    SS = NULL;
    /*初始化这个栈*/
    InitStack(SS);
    /*将数据压入栈内*/
    for(i=0;i<10;i++)
        Push(SS,i);
    /*以出栈顺序打印栈*/
    Print(SS);
    printf("/n");
    /*弹出栈顶元素,并再次打印栈*/
    Pop(SS);
    Pop(SS);
    Print(SS);
    /*返回栈顶元素*/
    i = GetTop(SS);
    printf("/nThe Top data is:%d/n",i);
    /*清空栈,并判断是否为空*/
    ClearStack(SS);
    IsEmpty(SS);
    /*销毁栈*/
    DestroyStack(SS);
}

运行后结果:

原文地址:https://www.cnblogs.com/CoderWayne/p/4483936.html