顺序栈的设计与实现
2012-12-17 23:42
232 查看
直接上代码
//2012-12-16 //顺序栈的设计与实现 //author:@quanwei #include<stdio.h> #include<stdlib.h> #define STACK_INIT_SIZE 4 #define STACKINCREMENT 10 typedef struct Stack{ int *base; int *top; int stackSize; }STACK; STACK *stack = (STACK *)malloc(sizeof(STACK)); /*****************************/ //函数名:CreatStack() //参数:无 //作用:构造一个空栈 //返回值:栈底指针 /*****************************/ int *CreatStack(){ stack->base = (int *)malloc(sizeof(int)*STACK_INIT_SIZE); if(stack == NULL) return 0; stack->stackSize = STACK_INIT_SIZE -1; //有一个空间空闲 stack->base; stack->top = stack->base; return stack->base; } /*****************************/ //函数名:PushStack(int elem) //参数:int elem 入栈元素 //作用:elem入栈 //返回值:无 /*****************************/ void PushStack(int elem){ if(stack->top - stack->base >= stack->stackSize){ //栈满追加存储空间 stack->base=(int *)realloc(stack->base,(stack->stackSize+STACKINCREMENT)* sizeof(int)); stack->top = stack->base + stack->stackSize; //确定栈顶地址 stack->stackSize += STACKINCREMENT; } stack->top++; *stack->top = elem; //stack->top = &elem 是错的 why? } /*****************************/ //函数名:PopStack(int *top) //参数:int *top 栈顶指针 //作用:出栈 //返回值:成功为出栈元素,失败提示错误 /*****************************/ int PopStack(int *top){ if(stack->base == stack->top){ printf("The stack is already full"); exit(0); } return *stack->top--; } /*****************************/ //函数名:GetTop() //参数:无 //作用:取栈顶元素 //返回值:成功为栈顶元素,栈为空提示错误 /*****************************/ int GetTop(){ if(stack->base == stack->top){ printf("The stack is already full"); exit(0); } return *(stack->top); } /*********** 测试程序 ************/ void main(){ char ch = 'y'; int num; CreatStack(); while(ch == 'y'){ printf("Input element"); scanf("%d",&num); PushStack(num); fflush(stdin); printf("go on?(y/n)"); scanf("%c",&ch); fflush(stdin); } printf("The top element of the stack is:%4d",GetTop()); printf("now pop stack\n"); while(stack->top != stack->base){ printf("%4d",PopStack(stack->top)); } }个人比较喜欢链栈
相关文章推荐
- 数据结构基础(6) --顺序栈的设计与实现
- 数据结构基础(6) --顺序栈的设计与实现
- 数据结构课程设计:顺序结构、动态链表结构下的一元多项式的加法、减法、乘法的实现
- [Java算法分析与设计]顺序循环队列的实现
- 队列顺序存储 - 设计与实现 - API函数
- 队列顺序存储 - 设计与实现 - API函数
- 数据结构基础(6) --顺序栈的设计与实现
- 数据结构课程设计--数组(顺序实现)
- 实现两个链表的合并 可变长顺序表设计 数据结构
- 线性表的顺序存储设计和实现 - API函数实现
- android 多控件顺序翻转动画设计实现
- C++[类设计]使用数组实现顺序栈
- 线性表顺序存储设计与实现_api函数实现
- 线性表的顺序存储设计和实现 - API函数实现
- 第二周 数据计算实现与顺序结构程序设计程序(一)
- C++数据结构与程序设计学习1-设计一个stack类(顺序实现)
- 栈的顺序存储 - 设计与实现 - API实现
- 栈的顺序存储 - 设计与实现 - API实现
- 栈的顺序存储 - 设计与实现 - API实现
- 线性表顺序存储设计与实现_框架搭建