本文共 1274 字,大约阅读时间需要 4 分钟。
#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef char SElemType;
typedef struct{
SElemType *base;
SElemType *top;
intstacklen;
}SqStack;
//建立空栈
int InitStack(SqStack &S,char*str){
S.stacklen=strlen(str);
S.base=(SElemType*)malloc(S.stacklen * sizeof(SElemType));
if(!S.base)exit(OVERFLOW);
S.top=S.base;
returnOK;
}
//括号匹配检测
int Check(SqStack &S1,SqStack &S2)
{
char*p;
for(S2.top=S2.base;S2.top<S2.base+S2.stacklen;S2.top++)
{
{ if(S1.top==S1.base)p=S1.top;elsep=S1.top-1;}
{
if(*(S2.top)=='('||*(S2.top)=='{'||*(S2.top)=='['){*(S1.top)=*(S2.top);S1.top++;}elseif(*(S2.top)==')'||*(S2.top)=='}'||*(S2.top)==']')
{
if((*(S2.top)==')'&&*p=='(')||(*(S2.top)=='}'&&*p=='{')||(*(S2.top)==']'&&*p=='[')){S1.top--;}else{printf("匹配的结果为:\n匹配失败!\n");return OK;}}}
}
if(S1.top==S1.base)
printf("匹配的结果为:\n匹配成功!\n");
returnOK;
}
//主函数
int main()
{
SqStack S1,S2;
chara[100];
printf("请输入要匹配的括号:\n");
gets(a);
InitStack(S2,a);
InitStack(S1,a);
strcpy(S2.base,a);
printf("要进行匹配的括号为:\n");
puts(S2.base);
printf("请按“”开始进行匹配:\n");
intselect;
scanf("%d",&select);
switch(select)
{
case1:
Check(S1,S2);break;
default:printf("您输入的数据有误!\n");
}
returnOK;
}
转载地址:http://usdaf.baihongyu.com/