【C--step by step④】栈

声明:

仅作自己练习学习用。

参考:

《数据结构》-严蔚敏版

直接上代码:

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

#define STACK_SIZE 10
#define STACK_INCREMENT 2

typedef struct {
    char *base; //栈底指针
    char *top;  //栈顶指针
    int stackSize;  //当前已分配的存储空间
}SqStack;

SqStack *this;  /*指向结构体对象的指针*/

typedef enum{
    false,
    true
}bool;

/*
 * 初始化
 */
bool initStack(SqStack *ps){
    this = ps;
    this->base = (char *) malloc(sizeof(char) * STACK_SIZE);
    if(NULL == this->base)
    {
        printf("Memory allocate Failure!\n");
        exit(-1);
    }
    this->top = this->base;
    this->stackSize = STACK_SIZE;

    return true;
}

/*
 * 销毁
 */
bool destroyStack(){
    this->base = NULL;
    this->top = NULL;
    this->stackSize = 0;

    free(this->top);
    free(this->base);
    free(this);

    return true;
}

bool clearStack(){
    this->top = this->base;

    return true;
}

bool isEmpty(){
    bool flag = (this->top == this->base) ? true : false;
    return flag;
}

bool isFull(){
    bool flag = (this->top - this->base >= this->stackSize) ? true : false;

    return flag;
}

int getSize(){
    return this->top - this->base;
}

char getTop(){
    return *this->top;
}

bool push(char e){
    bool flag = isFull();
    if(flag)
    {
        this->base = (char *) realloc(this->base,
                (this->stackSize + STACK_INCREMENT)* sizeof(char));
        if(NULL == this->base)
        {
            printf("Memory allocate Failure!\n");
            exit(-1);
        }
        this->top = this->base + this->stackSize;
        this->stackSize += STACK_INCREMENT;
    }

    this->top++;
    *this->top = e;
//    this->top = &e;
    this->stackSize++;


    return true;
}

/*
 * 弹出栈顶元素
 */
char pop()
{
    char e;
    if(isEmpty())
    {
        printf("Stack is Empty!");
        exit(-1);
    }
    e = *this->top;
    this->top--;
    this->stackSize--;

    return e;
}

/*
 * 打印输出栈中元素
 * top to base
 */
void display(char e){
    printf("the value is --> %c; \n", e);
}

int main() {
    SqStack *ps = NULL;
    ps = (SqStack *) malloc(sizeof(SqStack));
    if(NULL == ps){
        printf("Memory allocate Failure!\n");
        exit(-1);
    }
    initStack(ps);
    push('a');
    push('b');
    push('2');

    char e = getTop();
    display(e);

    int size = getSize();
    printf("there are %d element in stack.\n", size);

/*
    while(!isEmpty()){
        char e = pop();
        display(e);
    }*/

    destroyStack();

    printf("done!\n");
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值