数据结构学习笔记-14

栈的基本操作

#include <stdio.h>
#include <stdlib.h>

#define ElemType int
#define STACK_INIT_SIZE 100
#define STACK_INCREMENT 10

typedef struct
{
    ElemType *base;
    ElemType *top;
       int stackSize;

}sqStack;

void initStack(sqStack *s)
{
    s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
    if( !s->base )
    {
        exit(0);
    }
    s->top = s->base;
    s->stackSize = STACK_INIT_SIZE;
}

void Push(sqStack *s, ElemType e)
{
    if(s->top - s->base >= s->stackSize)
    {
        s->base = realloc(s->base, (s->stackSize+STACK_INCREMENT)*sizeof(ElemType));

        if( !s->base )
        {
            exit(0);
        }

        s->top = s->base + s->stackSize;
        s->stackSize = s->stackSize+STACK_INCREMENT;
    }

    *(s->top) = e;
    s->top++;

}

ElemType * Pop(sqStack *s, ElemType *e)
{
    if(s->top == s->base)
        return;

    *e = *--(s->top);

    return e;
}

void DestroyStack(sqStack *s)
{
    int i, len;
    len = s->stackSize;

    for(i=0; i<len; i++)
    {
        free(s->base);
        s->base++;
    }

    s->base = s->top = NULL;
    s->stackSize = 0;
}

void ClearStack(sqStack *s)
{
    s->top = s->base;
}


int StackLen(sqStack s)
{
    return (s.top - s.base);
}

int main()
{

    return 0;
}