假设一个算术表达式中包含圆括号、方括号两种类型的括号,试编写一个判断表达式中括号是否匹配的程序,匹配返回Match succeed!,否则返回Match false!。
例
[1+2*(3+4*(5+6))]括号匹配
(1+2)(1+2[(1+2)+3)括号不匹配
输入:
包含圆括号、方括号两种类型括号的算术表达式
输出:
匹配输出:Match succeed!
不匹配输出 :Match false!
例
输入:
[1+2* (3+4*(5+6))]
输出:
Match succeed!
输入:
(1+2)(1+2[(1+2)+3)
输出:
Match false!
输入:
([)]
输出:
Match false!
输入:
[(())]
输出:
Match succeed!
代码
#include<iostream>
using namespace std;
struct Stack
{
Stack*father, *son;
int brace;
};
void StackPush(Stack*&p, int &a)
{
Stack*NewStack = new Stack();
NewStack->brace = a;
p->son = NewStack;
NewStack->father = p;
p = p->son;
}
int StackPop(Stack*&p)
{
return p->brace;
}
int StackEmpty(Stack*&p)
{
return p->brace == 0 ? 1 : 0;
}
int main()
{
Stack BraceStack,*p;
BraceStack.brace = 0;
BraceStack.father = BraceStack.son = NULL;
int ch, Spop, Flag = 1;;
p = &BraceStack;
while (ch = getchar())
{
if (ch == '\n')
break;
switch (ch)
{
case '(':
StackPush(p, ch); break;
case '[':
StackPush(p, ch); break;
case ')':
{
Spop = StackPop(p);
if ((Spop == '('&&ch == ')') || (Spop == '['&&ch == ']'))
{
p = p->father;
delete p->son;
p->son = NULL;
}
else
Flag = 0;
break;
}
case ']':
{
Spop = StackPop(p);
if ((Spop == '('&&ch == ')') || (Spop == '['&&ch == ']'))
{
p = p->father;
delete p->son;
p->son = NULL;
}
else
Flag = 0;
break;
}
}
}
if (!StackEmpty(p))
Flag = 0;
printf(Flag ? "Match succeed!\n" : "Match false!\n");
//system("pause");
return 0;
}