您的位置:首页 > 编程语言 > C语言/C++

C语言学习:通过数组来实现栈

2014-02-02 23:08 274 查看
通过数组自动扩容来实现动态的堆栈结构,代码如下:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: