括号匹配问题(栈)![](https://i-blog.csdnimg.cn/blog_migrate/566adf83b9573a58b943ab3d3dc8b17e.png)
#include <iostream>
using namespace std;
#define maxSize 100
template<class T>
class SqStack{
private:
int base;
int top;
T *data;
public:
int top1() {
return top;
}
SqStack(){
data = new T[maxSize];
base = 0;
top = -1;
}
~SqStack() {
delete[] data;
}
bool Push(T ch) {
if (top >= maxSize-1) { // 判断是否栈满
return false;
}
top++;
data[top] = ch;
return true;
}
bool Pop() {
if (top < base) {
return false;
}
top--;
return true;
}
T getTop() {
if (top >= base) {
return data[top];
}
else {
return -1;
}
}
bool IsEmpty() {
if (top < base) {
return true;
}
else return false;
}
};
int main() {
SqStack<char> stk;
char ch;
cin >> ch;
while (ch != '#') {
if (ch == '(' || ch == '[' || ch == '{') {
stk.Push(ch);
}
cin >> ch;
if (ch == ')' || ch == '}' || ch == ']') {
if ((int)(stk.getTop()) == (int)ch - 1 || (int)(stk.getTop()) == (int)ch - 2) {
stk.Pop();
}
else {
stk.Push(ch);
}
}
}
if (stk.top1() == -1) {
cout << "匹配" << endl;
return 0;
}
cout << "不匹配" << endl;
return 0;
}