通过数组自动扩容来实现动态的堆栈结构,代码如下:
stack.h
#include<stdlib.h>
#define STACK_TYPE int
void create_stack(size_t size);
void destroy_stack(void);
void push(STACK_TYPE value);
STACK_TYPE pop(void);
int is_empty(void);
int is_full(void);
stack.c
#include "stack.h"
#include <stdio.h>
STACK_TYPE * copy(STACK_TYPE *s);
static STACK_TYPE *stack;
static size_t stack_size;
static size_t top_index;
void create_stack(size_t size) {
stack_size = size;
stack = (STACK_TYPE *) malloc(stack_size * sizeof(STACK_TYPE));
if(stack == NULL) {
printf("failed to initialize slack");
exit(-1);
}
}
void destroy_stack(void) {
top_index = 0;
stack_size = 0;
free(stack);
stack = NULL;
}
void push(STACK_TYPE value) {
if(!is_full()) {
stack[top_index++] = value;
} else {
stack_size *= 2;
stack = copy(stack);
stack[top_index++] = value;
}
}
STACK_TYPE pop(void) {
if(is_empty()) {
printf("stack is already empty");
exit(-1);
}
return stack[--top_index];
}
int is_empty(void) {
return top_index == 0;
}
int is_full(void) {
return top_index + 1 == stack_size;
}
STACK_TYPE * copy(STACK_TYPE *s) {
STACK_TYPE *q = (STACK_TYPE *) malloc(stack_size * sizeof(STACK_TYPE) * 2);
if(q == NULL) {
printf("failed to initialize slack");
exit(-1);
}
int i;
for(i = 0; i < stack_size; i++) {
*(q+i) = *(s+i);
}
return q;
}
void print(void) {
int i;
for(i = 0; i < top_index; i++) {
printf("%d ",stack[i]);
}
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;
}