#include #define maxstacksize 100
typedef char datatype;
#include "seqstack.h"
void expiscorrect(char exp[], int n)
//判断有n个字符的字符串exp左右括号是否配对正确
{
seqstack mystack; //定义链式堆栈
int i;
char c;
stackinitiate(&mystack);
for(i = 0; i < n; i++)
{
if((exp[i] == '(') || (exp[i] == '[') || (exp[i] == '{'))
stackpush(&mystack, exp[i]); //入栈
else if(exp[i] == ')' && stacknotempty(mystack)
&& stacktop(mystack, &c) && c == '(')
stackpop(&mystack, &c); //出栈
else if(exp[i] == ')' && stacknotempty(mystack)
&& stacktop(mystack, &c) && c != '(')
{
printf("左右括号配对次序不正确!\n");
return;
}
else if(exp[i] == ']' && stacknotempty(mystack)
&& stacktop(mystack, &c) && c == '[')
stackpop(&mystack, &c); //出栈
else if(exp[i] == ']' && stacknotempty(mystack)
&& stacktop(mystack, &c) && c != '[')
{
printf("左右括号配对次序不正确!\n");
return;
}
else if(exp[i] == '}' && stacknotempty(mystack)
&& stacktop(mystack, &c) && c == '{')
stackpop(&mystack, &c); //出栈
else if(exp[i] == '}' && stacknotempty(mystack)
&& stacktop(mystack, &c) && c != '{')
{
printf("左右括号配对次序不正确!\n");
return;
}
else if(((exp[i] == ')') || (exp[i] == ']') || (exp[i] == '}'))
&& !stacknotempty(mystack))
{
printf("右括号多于左括号!\n");
return;
}
}
if(stacknotempty(mystack))
printf("左括号多于右括号!\n");
else
printf("左右括号匹配正确!\n");
}
void main(void)
{
char a[] = "(())abc{[)(]}"; //测试例子1。左右括号配对次序不正确
char b[] = "(()))abc{[]}"; //测试例子2。右括号多于左括号
char c[] = "(()()abc{[]}"; //测试例子3。左括号多于右括号
char d[] = "(())abc{[]}"; //测试例子4。左右括号匹配正确
int n1 = strlen(a);
int n2 = strlen(b);
int n3 = strlen(c);
int n4 = strlen(d);
expiscorrect(a, n1);
expiscorrect(b, n2);
expiscorrect(c, n3);
expiscorrect(d, n4);
}
二者放于同一目录下即可