#include <iostream>
//顺序栈
struct Stack
{
char a[100];
int num;
};
//入栈
void push(Stack &s, char c)
{
s.a[s.num++] = c;
}
//出栈
void pop(Stack &s, char &c)
{
c = s.a[--s.num];
}
int main(int argc, char const *argv[])
{
Stack s;
int flag = false;
char test[] = {'(', '(', ']', ')'};
s.num = 0;
for (int i = 0; i < 5; i++)
{
if (test[i] == '(' || test[i] == '[')
{
push(s, test[i]);
continue;
}
//不是左括号
if (s.num == 0)
{
std::cout << "没有左括号匹配右括号:" << s.num << std::endl;
flag = true;
break;
}
char t;
pop(s, t);
if ((test[i] == ')' && t != '(') || (test[i] == ']' && t != ']'))
{
std::cout << "括号不匹配,位置:" << i << "\t左括号:" << t << "\t右括号:" << test[i] << std::endl;
flag = true;
break;
}
}
if (s.num != 0 && !flag)
std::cout << "有多余的左括号:" << s.num << std::endl;
return 0;
}
运行结果:
括号不匹配,位置:2 左括号:( 右括号:]