55 lines
939 B
C++
55 lines
939 B
C++
#include <string>
|
|
#include <iostream>
|
|
using namespace std;
|
|
#include "LinkStack.h"
|
|
|
|
bool match(string exp)
|
|
{
|
|
SNode<char>* S;
|
|
InitStack(S);
|
|
int flag = 1, i = 0;
|
|
char ch, e, x;
|
|
ch = exp[i++];
|
|
while (ch != '#' && flag)
|
|
{
|
|
switch (ch)
|
|
{
|
|
case '[':
|
|
case '(':
|
|
cout << "左括号进栈!" << endl;
|
|
Push(S, ch);
|
|
break;
|
|
case ')':
|
|
GetTop(S, e);
|
|
if (!StackEmpty(S) && e == '(')
|
|
{
|
|
Pop(S, x);
|
|
cout << "右括号出栈!" << endl;
|
|
}
|
|
else flag = 0;
|
|
break;
|
|
case ']':
|
|
GetTop(S, e);
|
|
if (!StackEmpty(S) && e == '[') Pop(S, x);
|
|
else flag = 0;
|
|
break;
|
|
}
|
|
ch = exp[i++];
|
|
}
|
|
if (StackEmpty(S) && flag) return true;
|
|
else return false;
|
|
}
|
|
|
|
int main()
|
|
{
|
|
int flag;
|
|
string exp;
|
|
cout << "请输入待匹配的表达式,以“#”结束:" << endl;
|
|
cin >> exp;
|
|
flag = match(exp);
|
|
if (flag) cout << "括号匹配成功!" << endl;
|
|
else cout << "括号匹配失败!" << endl;
|
|
return 0;
|
|
}
|
|
|