#include <iostream>
using namespace std;
// 定义;
struct Stack {
char data;
Stack *next;
};
// 初始化;
Stack *Init() {
Stack *top;
top = new Stack();
top->next = NULL;
return top;
}
// 进栈;
void Push(Stack *top, char e) {
Stack *p;
p = new Stack();
if (!p)
return ;
p->next = top->next;
p->data = e;
top->next = p;
}
// 出栈;
char Pop(Stack *top) {
Stack *p;
char e;
if (top->next == NULL)
return 0;
p = top->next ;
e = p->data;
top->next = p->next;
delete p;
return e;
}
int main() {
Stack *s, *top;
char ch, x;
int m, n, t;
m = n = t = 0;
top = s = Init();
// 输入一个字符,判断是‘)’,‘]’(若是则进栈);若是‘(’,‘[’则从栈顶取出值进行匹配;
while ((ch = getchar()) != 10) {
if (ch == '[' || ch == '(') {
Push(s, ch);
++m;
}
else if (ch == ']') {
x = Pop(s);
if (x != '[') {
++n;
cout << "']'不匹配\n";
}
}
else if (ch == ')') {
x = Pop(s);
if (x != '(') {
++n;
cout << "')'不匹配\n";
}
}
}
cout << "括号要匹配的数量:\n";
cout << m << endl;
cout << "括号不匹配的数量:\n";
cout << n << endl;
cout << "括号匹配的数量:\n";
cout << m - n << endl;
// 如果括号两边的数量不相符合,则多于的没有匹配的有多少;
if (top->next != NULL) {
while (top->next != NULL) {
top = top->next;
++t;
}
}
cout << "如果两边括号数量不匹配,输出不能匹配的数量:\n";
cout << t << endl;
return 0;
}