//SeqStack.h
typedef char ElemType;
#define MaxSize 100
typedef struct
{
ElemType data[MaxSize];
int top;
}SeqStack;
// 初始化栈
extern void InitStack(SeqStack *&s);
// 销毁栈
extern void DestroyStack(SeqStack *&s);
// 判断栈是否为空
extern int StackEmpty(SeqStack *s);
// 入栈
extern void PushStack(SeqStack *&s, ElemType e);
// 出栈
extern ElemType PopStack(SeqStack *&s);
// 取栈顶元素
extern ElemType GetTop(SeqStack *&s, ElemType &e);
//SeqStack.cpp
//SeqStack.cpp
#include<malloc.h>
#include<stdio.h>
#include"SeqStack.h"
// 初始化栈
void InitStack(SeqStack *&s)
{
s = (SeqStack *)malloc(sizeof(SeqStack));
s->top = -1;
}
// 销毁栈
void DestroyStack(SeqStack *&s)
{
free(s);
}
// 判断栈是否为空
int StackEmpty(SeqStack *s)
{
if ( s->top == -1 )
return 1;
else
return 0;
}
// 入栈
void PushStack(SeqStack *&s, ElemType e)
{
if ( s->top == MaxSize - 1 )
printf("Stack full\n");
else
{
s->top++;
s->data[s->top] = e;
}
}
// 出栈
ElemType PopStack(SeqStack *&s )
{
ElemType e;
if ( s->top == -1 )
{
printf("Stack empty!\n");
return NULL;
}
else
{
e = s->data[s->top];
s->top--;
return e;
}
}
// 取栈顶元素
ElemType GetTop(SeqStack *&s, ElemType &e)
{
if ( s->top == -1 )
{
printf("Stack Empyt!\n");
return NULL;
}
else
{
e = s->data[s->top];
return e;
}
}
//main.cpp
//main.c
#include<malloc.h>
#include<stdio.h>
#include"SeqStack.h"
int main()
{
SeqStack *s;
ElemType e;
s = (SeqStack *)malloc(sizeof(SeqStack));
printf("\n栈s的基本运算如下:\n");
printf("[1]初始化栈s: \n");
InitStack(s);
printf("[2]栈为 %s \n",(StackEmpty(s) ? "空":"非空"));
printf("\n[3]依次入栈元素: a, b, c, d, e\n");
PushStack(s,'a');
PushStack(s,'b');
PushStack(s,'c');
PushStack(s,'d');
PushStack(s,'e');
printf("[4]栈为 %s \n",(StackEmpty(s) ? "空":"非空"));
printf("\n[5]出栈序列: ");
while(!StackEmpty(s))
{
printf("%c ",PopStack(s));
}
printf("\n[6]栈为 %s \n",(StackEmpty(s) ? "空":"非空"));
printf("[7]释放栈!\n");
DestroyStack(s);
return 0;
}