1、头文件:stack.h
#include<iostream>
#include<malloc.h>
using namespace std;
typedef int Status;
typedef char ElemType;
#define ok 1
#define error 0
#define Stack_Init_Size 10
#define Stack_ADD 10
#define flow 0
typedef struct{
ElemType* base;
ElemType* top;
int stacksize;
}SqStack;
//初始化,构造一个空栈
Status InitStack(SqStack& S);
//如果栈不为空,就获取栈顶数据
Status GetTop(const SqStack& S, ElemType& e);
//压栈
Status Push(SqStack& S, ElemType& e);
//如果栈顶不为空,弹出栈顶数据
Status Pop(SqStack& S, ElemType& e);
//置为空栈
Status StackEmpty(SqStack& S);
//打印栈中的数据
Status Print(const SqStack& S);
2、源文件stack.cpp:
#include "stack.h"
//初始化,构造一个空栈
Status InitStack(SqStack& S){
S.base = NULL;
S.top = NULL;
S.base = (ElemType *)malloc(Stack_Init_Size * sizeof(ElemType));
if(!S.base) exit(flow);
S.top = S.base;
S.stacksize = Stack_Init_Size;
return ok;
}
//如果栈不为空,就获取栈顶数据
Status GetTop(const SqStack& S, ElemType& e){
if (S.top == S.base) return error;
e = *(S.top-1);
return ok;
}
//压栈
Status Push(SqStack& S, ElemType& e){
//计算栈顶和栈底的距离
int length = S.top - S.base;
if(S.stacksize == length){
S.base = (ElemType*)realloc(S.base, (Stack_ADD + S.stacksize) * sizeof(ElemType));
S.top = S.base + S.stacksize;
S.stacksize = S.stacksize + Stack_ADD;
if(!S.base) exit(flow);
}
*S.top = e;
S.top++;
return ok;
}
//如果栈顶不为空,弹出栈顶数据
Status Pop( SqStack& S, ElemType& e){
if (S.top == S.base) return error;
e = *(S.top-1);
S.top--;
return ok;
}
//将站置空
Status StackEmpty(SqStack& S)
{
if (S.top == S.base){
return ok;
}else{
free(S.base);
S.top = S.base = NULL;
return error;
}
}
//打印栈中数据
Status Print(const SqStack& S){
if(S.base == S.top){
cout<<"这是一个空栈,没有数据"<<endl;
return error;
}else{
ElemType* p;
p = S.base;
cout<<"栈中的数据如下:"<<endl;
while(p != S.top){
cout<<*p<<" ";
p++;
}
cout<<endl;
return ok;
}
}
3、测试文件test.cpp:
#include "stack.h"
#include<time.h>
#include<stdio.h>
#include<string>
int main(void){
SqStack S;
ElemType e, e1;
int n;
InitStack(S);
cout<<"请输入你要输入括号个数,必须是偶数"<<endl;
cin>>n;
cout<<"请输入"<<n<<"个括号"<<endl;
for(int i=0; i<n; i++){
cin>>e;
if(S.top - S.base >= 1){
GetTop(S, e1);
if(e1+2 == e)
Pop(S, e1);
}else{
Push(S, e);
}
}
if(S.base == S.top){
cout<<"括号匹配是对的"<<endl;
}else{
cout<<"括号不匹配"<<endl;
}
free(S.base);
}