疯狂指针(3)

同样,我们再创建一个关于栈的类

抽象出栈的方法构成接口

//Stack.h
Class Stack{
    int length;
    int size;
    Class Element **bottom;
    void (*destroy)(Class Stack *this);
    void (*clear)(Class Stack *this);
    Boolean (*isEmpty)(Class Stack *this);
    Boolean (*isFull)(Class Stack *this);
    Object (*pop)(Class Stack *this);
    Status (*push)(Class Stack *this,Object value);
    Object (*getTop)(Class Stack *this);
};

 

实例化接口Stack.c

void Stack_Destroy(Class Stack *this){
        this->clear(this);
        free(this);
}


void Stack_Clear(Class Stack *this){
        while(this->isEmpty(this)!=True)
            this->pop(this);
}


Boolean Stack_IsEmpty(Class Stack *this){
        if(this->length==0)
            return True;
        else
            return False;
}

Boolean Stack_IsFull(Class Stack *this){
        if(this->length==this->size)
            return True;
        else
            return False;
}

Object Stack_Pop(Class Stack *this){
    Class Element *element = *(this->bottom+this->length);
    Object object = this->getTop(this);
        if(this->isEmpty(this)==True)
            return Null;
        free(element);
        this->length--;
        return object;
}


Status Stack_Push(Class Stack *this,Object value){
        if(this->isFull(this)==True)
            return Fail;
        this->length++;
        this->bottom[this->length] = Element_new(value);
        return Success;
}

Object Stack_GetTop(Class Stack *this){
        return (*(this->bottom+this->length))->value;
}

Class Stack *Stack_new(int size){
    Class Stack *this = (Class Stack*)malloc(sizeof(Class Stack));
        this->bottom = (Class Element**)malloc(sizeof(Class Element*)*size);
        this->size = size;
        this->length = 0;
        this->destroy = Stack_Destroy;
        this->clear = Stack_Clear;
        this->isEmpty = Stack_IsEmpty;
        this->isFull = Stack_IsFull;
        this->pop = Stack_Pop;
        this->push = Stack_Push;
        this->getTop = Stack_GetTop;
        return this;
}

 

演示程序:

#include "const.h"
#include "Element.h"
#include "Element.c"
#include "Stack.h"
#include "Stack.c"


int main(void){
    Class Stack *stack = Stack_new(100);
    Object temp;

        stack->push(stack,Integer_new(100));
        stack->push(stack,String_new("Hello MM!"));

        temp = stack->pop(stack);
        printf("%s/n",(String)temp);
        free(temp);
       
        temp = stack->pop(stack);
        printf("%d/n",*(Integer)temp);
        free(temp);
       
        stack->destroy(stack);
        return 0;
}

输出:
Hello MM!
100

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值