接上例:http://blog.csdn.net/kunshan_shenbin/article/details/18903731
stack.h还是上例中的代码,不需要变化。
stack.c代码如下:
#include "stack.h"
#include <stdio.h>
typedef struct STACK_NODE {
STACK_TYPE value;
struct STACK_NODE *next;
} StackNode;
static StackNode *stack = NULL;
void create_stack(size_t size) {}
void destroy_stack(void) {
while(!is_empty()) {
pop();
}
}
void push(STACK_TYPE value) {
StackNode *stack_node = (StackNode *) malloc(sizeof(StackNode));
if(stack_node == NULL) {
printf("failed to initialize slack node");
exit(-1);
}
stack_node->value = value;
stack_node->next = stack;
stack = stack_node;
}
STACK_TYPE pop(void) {
if(is_empty()) {
printf("stack is already empty");
exit(-1);
}
StackNode *stack_node = stack;
STACK_TYPE stack_value = stack_node->value;
stack = stack_node->next;
free(stack_node);
return stack_value;
}
int is_empty(void) {
return stack == NULL;
}
int is_full(void) {
return 0;
}
void print(void) {
StackNode *stack_node = stack;
while(stack_node != NULL)
{
printf("%d ", stack_node->value);
stack_node = stack_node->next;
}
printf("\n");
}
int main() {
create_stack(3);
push(1);
push(2);
push(3);
push(4);
print();
printf("%d\n",pop());
printf("%d\n",pop());
printf("%d\n",pop());
print();
printf("%d\n",pop());
printf("%d\n",pop());
print();
destroy_stack();
return 0;
}