

1 #ifndef SQSTACK_H_H 2 #define SQSTACK_H_H 3 /* SqStack.h 栈的顺序存储表示 */ 4 #define STACK_INIT_SIZE 10 /* 存储空间初始分配量 */ 5 #define STACK_INCREMENT 2 /* 存储空间分配增量 */ 6 7 /* 用户自定义SElemType 栈元素类型*/ 8 typedef int SElemType; 9 10 /* 用户自定义SElemType 栈元素类型*/ 11 12 typedef struct SqStack 13 { 14 SElemType *base; /* 在栈构造之前和销毁之后,base的值为NULL */ 15 SElemType *top; /* 栈顶指针 */ 16 int stacksize; /* 当前已分配的存储空间,以元素为单位 */ 17 }SqStack; /* 顺序栈 */ 18 Status InitStack(SqStack &S); 19 Status DestroyStack(SqStack &S); 20 Status ClearStack(SqStack &S); 21 Status StackEmpty(SqStack S); 22 int StackLength(SqStack S); 23 Status GetTop(SqStack S,SElemType &e); 24 Status Push(SqStack &S,SElemType e); 25 Status Pop(SqStack &S,SElemType &e); 26 Status StackTraverse(SqStack S,Status(*visit)(SElemType)); 27 #endif

#include "UsuHead.h" #include "SqStack.h" Status visit(SElemType e) { printf("%d",e); return OK; } void main() { int j; SqStack s; SElemType e; if(InitStack(s)==OK) for(j=1;j<=12;j++) Push(s,j); printf("栈中元素依次为:"); StackTraverse(s,visit); Pop(s,e); printf("弹出的栈顶元素 e=%d\n",e); printf("栈空否:%d(1:空 0:否)",StackEmpty(s)); GetTop(s,e); printf("栈顶元素e=%d 栈的长度为%d\n",e,StackLength(s)); ClearStack(s); printf("清空后,栈空否:%d(1:空 0:否)\n",StackEmpty(s)); DestroyStack(s); printf("销毁栈后,s.top-%u s.base=%u s.stacksize=%d\n",s.top,s.base ,s.stacksize ); }

#ifndef USUHEAD_H_H #define USUHEAD_H_H /*UsuHead.h*/ #include<string.h> #include<ctype.h> #include<malloc.h> /* malloc()等 */ #include<limits.h> /* INT_MAX等 */ #include<stdio.h> /* EOF(=^Z或F6),NULL */ #include<stdlib.h> /* atoi() */ #include<io.h> /* eof() */ #include<math.h> /* floor(),ceil(),abs() */ #include<process.h> /* exit() */ /* 函数结果状态代码 */ #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 /* #define OVERFLOW -2 因为在math.h中已定义OVERFLOW的值为3,故去掉此行 */ typedef int Status; /* Status是函数的类型,其值是函数结果状态代码,如OK等 */ typedef int Boolean; /* Boolean是布尔类型,其值是TRUE或FALSE */ #endif
)
(vc++6.0 win32 console application)实现