代码
#include "iostream"
#include <stdlib.h>
#include <math.h>
using namespace std;
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define STACK_SIZE 20
#define STACK_INCREMENT 10
typedef int Status;
typedef int Elemtype;
typedef struct
{
Elemtype *base;
Elemtype *top;
int stackSize;
} sqStack;
void Init_Stack(sqStack *s)
{
s->base = (Elemtype *)malloc(STACK_SIZE *sizeof(Elemtype));
if (!s->base)
{
exit(0);
}
s->top = s->base;
s->stackSize = STACK_SIZE;
}
void Push_Stack(sqStack *s, Elemtype e)
{
if (s->top - s->base >= s->stackSize)
{
s->base = (Elemtype *)realloc(s->base, (s->stackSize + STACK_INCREMENT) * sizeof(Elemtype));
if (!s->base)
{
exit(0);
}
s->top = s->base + s->stackSize;
s->stackSize = s->stackSize + STACK_INCREMENT;
}
*(s->top) = e;
s->top++;
}
void Pop_Stack(sqStack *s, Elemtype *e)
{
if (s->top == s->base)
{
exit(0);
}
*e = *--(s->top);
}
Status Destory_Stack(sqStack *s)
{
int i;
for (i = 0; i < s->stackSize; i++)
{
free(s->base);
s->base++;
}
s->base = s->top = NULL;
s->stackSize = 0;
return OK;
}
int Length_Stack(sqStack *s)
{
return(s->top - s->base);
}
void main()
{
sqStack s;
Elemtype e;
int len, i;
Init_Stack(&s);
Push_Stack(&s, 1);
Push_Stack(&s, 2);
Push_Stack(&s, 3);
Push_Stack(&s, 4);
Push_Stack(&s, 5);
Push_Stack(&s, 6);
cout << "the length of the stack currently:";
cout << Length_Stack(&s) << endl;
len = Length_Stack(&s);
cout << "出栈顺序为:";
for (i = 0; i < len; i++)
{
Pop_Stack(&s, &e);
cout << e << " ";
}
cout << endl;
system("pause");
}
截图
