利用顺序栈实现括号匹配

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>


#define TRUE 1
#define FALSE 0
#define OVERFLOW 0
#define OK 1
#define ERROR 0


#define STACK_INIT_SIZE 300//存储空间初始化分配量
#define STACKINCREMENT 30//存储空间分配增量
#define MAXLEN 10
typedef int Status;
 




typedef char ElemType;


typedef struct{           //构建一个栈
ElemType  *base;    
    ElemType  *top;  
    int  stacksize;    
  } SqStack;




Status InitStack(SqStack &S) //初始化栈
{
S.base=(ElemType*)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(!S.base) exit(OVERFLOW);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
};


Status Push(SqStack &S, ElemType e){  //入栈
if (S.top-S.base>=S.stacksize){//栈满,追加存储空间
S.base=(ElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof (ElemType));
if(!S.base)exit(OVERFLOW); //存储分配失败
       S.top =S.base+S.stacksize;
       S.stacksize+=STACKINCREMENT;
}
   *S.top++ =e;
    return OK;

}




Status Pop(SqStack &S,ElemType &e) {//出栈
    if(S.top==S.base)
return ERROR;
    e=* --S.top;
    return OK;
}




Status StackEmpty(SqStack S) //判断栈是否为空
{
if(S.top==S.base) return TRUE;
else return FALSE;
};




Status DestroyStack(SqStack &S)//摧毁栈
{
free(S.base);
S.base=NULL;
S.top=NULL;
S.stacksize=0;
return OK;
}


int StackLength(SqStack S) //求栈长
{
return S.top-S.base;
}


Status GetTop(SqStack S, ElemType &e)  //取栈顶元素
{
if (S.top==S.base) return ERROR;
else
e=*(S.top-1);
return OK;
}


Status ClearStack(SqStack &S) //清空栈
{
S.top = S.base;
return OK;
}




Status StackTravers(SqStack S, Status (*visit)(ElemType)) //遍历栈
{
ElemType *p=S.base;
if (S.top==S.base) return ERROR;
do
{
if (!visit(*p)) return ERROR;
}while (p++ !=S.top );
return OK;
}
Status matching(SqStack S,char *exp)
{
int i=0;
char e;
while(i<strlen(exp)) {
     switch (exp[i]) {
case '(':
case '[':
case '{':
{Push(S,exp[i]); i++; break;}
    case ')':
    case ']':
        case '}':
if(StackEmpty(S)) 
{
printf("括号匹配失败");
return ERROR;
}
else 
{
GetTop(S,e);
if((exp[i]==')' && e=='(') || (exp[i]=='}' && e=='{') || (exp[i]==']' && e=='[')) 
{
Pop(S,e);
i++;
break;
}
else 
{
printf("括号匹配失败");
return ERROR;
break;
}
}
}
}
  if (StackEmpty(S))
{
printf("括号匹配成功");
return OK;
}
else
printf("括号匹配失败");
return ERROR;

}



void main(){


char str[100];
SqStack S;
InitStack (S);
printf("请输入括号\n");
gets(str);
matching(S,str);
}

猜你喜欢

转载自blog.csdn.net/wangjianxin97/article/details/78494018
今日推荐