純C語言實現順序棧

#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100

typedef int SElemType;

typedef struct {
    SElemType *base;
    SElemType *top;
    int stackSize;
}SqStack;

SqStack *InitStack(SqStack *S);//初始化
SqStack *DestroyStack(SqStack*S);//銷燬
void ClearStack(SqStack*S);//清空
int StackEmpty(SqStack*S);//判空
int StackLength(SqStack*S);//棧長度
SElemType GetTop(SqStack*S);//獲取棧頂元素,不修改指針位置
int Push(SqStack*S, SElemType e);//插入棧頂
int Pop(SqStack *S, SElemType *e);//刪除棧頂
void StackTraverse(SqStack *S);//從棧頂依次遍歷


//初始化,返回指向棧的指針
SqStack * InitStack(SqStack *S){
    S = (SqStack *)malloc(sizeof(SqStack));
    S->base = (SElemType *)malloc(sizeof(SElemType)*MAXSIZE);
    if(!S->base){
        printf("空間不足初始化失敗\n");
        return NULL;
    }
    S->top = S->base;
    S->stackSize = MAXSIZE;
    printf("初始化成功\n");
    return S;
}

//銷燬
SqStack *DestroyStack(SqStack*S){
    free(S->base);
    free(S);
    printf("已銷燬\n");
    return NULL;
}

//清空
void ClearStack(SqStack*S){
    printf("清空\n");
    SElemType *p = S->top;
    while(p >= S->base){
        *p--=0;
    }
    printf("清空成功\n");
}

//判空
int StackEmpty(SqStack*S){
    return (S->base == S->top);
}

//返回棧長度
int StackLength(SqStack*S){
    return S->top-S->base;
}

//獲取棧頂元素,不修改指針位置
SElemType GetTop(SqStack*S){
    if(S->top != S->base)
        return *(S->top - 1);
}

//插入棧頂,返回是否插入成功的狀態
int Push(SqStack*S, SElemType e){
    if(S->top - S->base == S->stackSize){
        printf("棧已滿,插入失敗\n");
        return 0;
    }
    //先賦值後動指針
    *S->top++=e;
    printf("%d元素入棧成功\n", e);
    return 1;
}

//刪除棧頂,返回是否刪除成功的狀態
int Pop(SqStack *S, SElemType *e){
    //棧空
    if(S->top == S->base){
        printf("空棧,刪除失敗\n");
        return 0;
    }
    //先動指針後賦值
    *e = *--S->top;
    printf("%d出棧成功\n", *e);
    return 1;
}

//從棧頂依次遍歷
void StackTraverse(SqStack *S){
    SElemType *p = S->top;
    while(p > S->base){
        p--;
        printf("%d ", *p);
    }
    printf("\n");
}



int main()
{
    SqStack *S = NULL;
    SElemType e;

    //初始化測試
    S = InitStack(S);

//    //判空測試
//    if(StackEmpty(S)) printf("空棧\n");
//
    //插入測試
    Push(S, 1);
    Push(S, 3);
    Push(S, 2);
    Push(S, 4);
    Push(S, 7);

//    //遍歷測試
//    StackTraverse(S);
//
//    //出棧測試
//    Pop(S, &e);
////    printf("測試e是否改變:%d\n",e);
//    StackTraverse(S);
//
//    //棧長測試
//    printf("棧長%d\n",StackLength(S));
//
//    //獲取棧頂元素測試
//    e = GetTop(S);
//    printf("棧頂元素是%d\n", e);
//    StackTraverse(S);
//
//    //清空測試
//    ClearStack(S);
//    if(StackEmpty(S)) printf("空棧\n");
//    StackTraverse(S);

    //銷燬測試
    S = DestroyStack(S);
    StackTraverse(S);

    return 0;
}
相關文章
相關標籤/搜索