2014年12月29日 星期一

Stack 堆疊

#define new

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

typedef enum boolean {
false,
true
} boolean;

typedef struct DataType {
int number;
} DataType;

#define Data(number) __Data_Setup(number)

DataType __Data_Setup(int number) {
DataType data;
data.number = number;
return data;
}

typedef struct Stack {
struct Stack *prev;
DataType data;
void (* push)(struct Stack *this, DataType data);
void (* clear)(struct Stack *this);
DataType (* pop)(struct Stack *this);
DataType (* top)(struct Stack *this);
boolean (* isFull)(struct Stack *this);
boolean (* isEmpty)(struct Stack *this);
} Stack;

void __Stack_push(Stack *this, DataType data);
void __Stack_clear(Stack *this);
DataType __Stack_pop(Stack *this);
DataType __Stack_top(Stack *this);
boolean __Stack_isFull(Stack *this);
boolean __Stack_isEmpty(Stack *this);
Stack *__Stack_Setup(void);

void __Stack_push(Stack *this, DataType data) {
Stack *stack = __Stack_Setup();
stack->data = data;
if(this->prev == NULL) {
this->prev = stack;
} else {
stack->prev = this->prev;
this->prev = stack;
}
}

void __Stack_clear(Stack *this) {
Stack *work = NULL;
Stack *self = this;
this = this->prev;
while(this != NULL) {
work = this;
this = this->prev;
free(work);
}
self->prev = NULL;
}

DataType __Stack_pop(Stack *this) {
if(this->prev!= NULL) {
DataType data = this->prev->data;
Stack *work = this->prev;
this->prev = work->prev;
free(work);
return data;
} else {
return Data(0);
}
}

DataType __Stack_top(Stack *this) {
return this->prev->data;
}

boolean __Stack_isFull(Stack *this) {
return false;
}

boolean __Stack_isEmpty(Stack *this) {
if(this->prev == NULL) {
return true;
} else {
return false;
}
}

#define Stack() __Stack_Setup()

Stack *__Stack_Setup() {
Stack *stack = (Stack *)malloc(sizeof(Stack));
stack->data = Data(0);
stack->prev = NULL;
stack->pop = &__Stack_pop;
stack->top = &__Stack_top;
stack->push = &__Stack_push;
stack->clear = &__Stack_clear;
stack->isFull = &__Stack_isFull;
stack->isEmpty = &__Stack_isEmpty;
return stack;
}