用栈实现括号匹配问题
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<malloc.h>
typedef char ElemType;
//定义基本类型
typedef int Statu;
//定义函数的返回状态
const int BASE_SIZE = 100;
//定义整个栈的基本大小
const int RESIZE = 40;
//定义栈的重新分配空间的大小
const int OK = 1;
//函数执行成功
const int ERROR = 0;
//函数执行失败
const int OVERFLOW = -1;//
溢出处理
/*定义栈的结构体*/
typedef struct SqStack
{
ElemType * base;
//栈底指针
ElemType * top;
//栈顶指针
int stacksize;
//栈的当前大小
}SqStack;
/*初始化一个栈*/
Statu InitStack(SqStack & S)
{
S.base = (ElemType*)malloc(sizeof(ElemType)*BASE_SIZE);//分配空间
if(!S.base)
//分配失败
{
printf("memory allocation has failed!\n");
exit(1);
}
S.top = S.base;//初始化为空栈
S.stacksize = BASE_SIZE;
//当前大小就是初始分配空间的大小
return OK;
}
/*获得栈顶元素*/
Statu GetTop(SqStack & S,ElemType & e)
{
/*if the stack is null return the ERROR otherwise return the value of the stac's top*/
if(S.top == S.base)
//栈为空
{
return ERROR;;
}
e = *(S.top-1);
return OK;
}
/*向栈中压入新的元素*/
Statu Push(SqStack & S,ElemType e)
{
if(S.top-S.base >= S.stacksize)//如果栈满了,就得重新追加空间
{
S.base=(ElemType*)realloc(S.base,(S.stacksize+RESIZE)*sizeof(ElemType));
//追加新的空间
if(!S.base)
{
printf("reallocation failure!\n");
exit(OVERFLOW);
}
S.top = S.base+S.stacksize;
//修改栈顶指针
S.stacksize += RESIZE;
//修改栈的当前大小
}
*S.top++=e;
//向栈中压入新的元素
return OK;
}
/*元素出栈*/
Statu Pop(SqStack & S,ElemType & e)
{
if(S.top == S.base) return ERROR;
//栈为空
e = *--S.top;
return OK;
}
/*销毁一个栈*/
void Destroy(SqStack & S)
{
free(S.base);
}
/*判断一个栈是否为空*/
bool IsEmpty(SqStack S)
{
return S.top == S.base;
}
/*(栈的应用)把一个十进制数转换为二进制数*/
void Translate(SqStack & S,int n_Translate)
{
for(;Push(S,n_Translate%2)&&(n_Translate/2);n_Translate /=2);
}
/*打印一个栈的所有元素*/
void print(SqStack & S)
{
ElemType *p = S.top;
while(p!=S.base)
{
printf("%d ",*(--p));
}
printf("\n");
}
/*(栈的应用)括号匹配*/
void BracketMatch(SqStack & S,char * str_Brackets)
{
Push(S,str_Brackets[0]);
char bracket1,bracket2;
for(int firdex =1;firdex < strlen(str_Brackets);firdex++)
{
bracket2 = str_Brackets[firdex];
if((bracket2==']' || bracket2==')' || bracket2=='}')&&!IsEmpty(S))
{
Pop(S,bracket1);
if(bracket1=='[' && bracket2==']');
else if(bracket1=='(' && bracket2==')');
else if(bracket1=='{' && bracket2=='}');
else
{
Push(S,bracket1);
Push(S,bracket2);
}
}
else
{
Push(S,bracket2);
}
}
if(IsEmpty(S))
printf("Brackets matched!\n");
else
printf("Brackets unmatched!\n");
}
int main(void)
{
printf("Please input a brackets string!");
char brackets[100];
scanf("%s",brackets);
SqStack S;
InitStack(S);
BracketMatch(S,brackets);
Destroy(S);
return 0;
}