同样,我们再创建一个关于栈的类
抽象出栈的方法构成接口
//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