C语言学习:通过数组来实现栈
2014-02-02 23:08
274 查看
通过数组自动扩容来实现动态的堆栈结构,代码如下:
stack.h
stack.c
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; }
相关文章推荐
- C语言通过指针和数组实现字符串倒序
- C语言学习历程(十五)结构体数组实现通讯录
- C语言学习之 通过指向函数的指针 实现函数的调用
- SQL学习笔记[5] - 通过分隔符解析方式实现向SQL存储过程传递数组参数
- 【数据结构】栈学习之数组实现(C语言)
- C语言学习:通过链表来实现栈
- 通过JNI实现C语言设置Java二维字符串数组并返回该字符串数组
- 通过冒泡排序(C语言实现)学习回调函数设计原理
- what's in string? c语言string类函数实现汇总 都是学习使用指针的好例子啊(算是读书摘抄和笔记吧)
- c语言学习零碎整理(7):数组名是指针吗?
- C语言学习第五章-数组(醉了)
- C语言学习之路之数组的一些浅见
- C语言中利用#define和#undef定义初始化数组,实现不同的初始化效果
- C语言中使用struct实现数组复制
- 向facebook学习,通过协程实现mysql查询的异步化
- iOS开发学习笔记 2-5 C语言部分 数组
- c语言学习笔记(4)struct和union:柔性数组存储斐波那契数列以及union判断系统大小端
- 纯c语言实现动态分配多维数组的方法
- 数据结构之数组(C语言实现)