栈(下)
2、静态存储
2.1类型定义及说明
#include "stdafx.h"
#include "malloc.h"
#include "stdlib.h"
#define OK 1
#define ERROR -1
#define OVERFLOW -2
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef int Status;
typedef int ElemType;
2.2存储方式
利用C语言库函数中的malloc和realloc函数可以对栈进行动态分配或在分配内存存储,其分配的是一组连续的内存空间。
2.2.1动态栈的定义
typedef struct Stack { ElemType *top; ElemType *base; int stacksize; int length; }Sqstack;
2.2.2栈的初始化
Status InitStack(Sqstack &S) { S.base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType)); if (!S.base)return ERROR; S.top = S.base; S.stacksize = STACK_INIT_SIZE; S.length = 0; return OK; }//栈的初始化
2.2.3圧栈
Status Push(Sqstack &S, ElemType e) { if (S.top - S.base >= S.stacksize - 1) { S.base = (ElemType *)realloc(S.base,(STACK_INIT_SIZE + STACKINCREMENT) * sizeof(ElemType)); if (!S.base)return ERROR; S.stacksize += STACKINCREMENT; } *S.top = e; S.top++;//栈顶指针加一,e成为新的栈顶 S.length++; return OK; }
2.2.4出栈
Status Pop(Sqstack &S, ElemType &e) { if (S.top == S.base) { printf("栈已经为空!"); return ERROR;//栈空,返回错误 } else { S.top--; S.length--; e = *S.top; return OK; } }/*出栈*/
2.2.5遍历
void Travel(Sqstack S) { if (S.top == S.base) { printf("栈空!"); } else { for (int i = 1; i < S.length; i++) { int a, b; a = *S.base; b = *(S.top--); printf("栈底:%d,栈顶:%d ,位置:%d\n\r", a ,b,S.length-i); } } }
2.2.6主函数
int main() { Sqstack S; int e; InitStack(S); for (int i = 1; i < 20; i++) { Push(S, 2*i); } Travel(S); Pop(S,e); printf("栈顶元素:%d", e); return 0; }
2.3调试结果
下一节将实现栈的链式存储。