C语言实现线性表栈

lsfreeing 2020-07-05

C语言实现线性表栈

//栈--线性表实现
#define ERROR -1

typedef int Position;
typedef int ElemType;
struct SNode{
    ElemType *Data;
    Position Top;
    int MaxSize;
};
typedef struct SNode *Stack;

Stack CreateStack(int MaxSize){
    Stack S = (Stack)malloc(sizeof(struct SNode));
    S->Data = (ElemType *)malloc(MaxSize * sizeof(ElementType));
    S->Top = -1;
    S->MaxSize = MaxSize;
    return S;
}

void DestroyStack(Stack S){
    if(S == NULL){
        return;
    }
    if(S->Data != NULL){
        free(S->Data);
    }
    free(S);
}

int IsEmpty(Stack S){
    return (S->Top == -1);
}

int IsFull(Stack S){
    return (S->Top == MaxSize);
}

int Push( Stack S, ElemType data){
    if(IsFull(S)){
        return 0;
    }
    S->Data[++(S->Top)] = data;
    return 1;
}

ElemType Pop( Stack S){
    if(IsEmpty()){
        return ERROR;
    }
    return (S->Data[S->Top--]);
}

相关推荐