括号匹配
作者:互联网
#include<iostream>//用栈实现(是否匹配 using namespace std; class SqStack { private: char* base; int stacksize; public: int top; SqStack(int m); void Push(char x); char Pop(); char Top(); }; SqStack::SqStack(int m) { base = new char [m]; if (base == NULL) { cout << "栈创建失败,退出" << endl; exit(1); } stacksize = m; top = -1; } void SqStack::Push(char x) { if (top == stacksize - 1) { throw"栈满,无法入栈"; } top++; base[top] = x; } char SqStack::Pop() { char x; if (top == -1) { throw"栈空,不能出栈"; } x = base[top--]; return x; } char SqStack::Top() { char x; if (top == -1) { throw"栈空"; } x = base[top]; return x; } int main() { SqStack A(100); int temp; int key = 0; string x; cin >> x; int length = x.length(); for (int i = 0; i < length; i++) { if (x[i] == '(' || x[i] == '[') { A.Push(x[i]); } else if (x[i] == ')') { if(A.top==-1) { A.Push(x[i]); key = 1;//多右括号) break; } else if (A.Top() == '[') { cout << "不匹配" << endl; key = 2;//[和)不匹配 break; } else A.Pop(); } else if (x[i] == ']') { if (A.top == -1) { A.Push(x[i]); key = 3;//多右括号] break; } else if (A.Top() == '(') { key = 4;//(和]不匹配 break; } else A.Pop(); } } if (A.top == -1) { cout << "匹配" << endl; } else { cout << "不匹配" << endl; while (A.top != -1) { if (key == 1 || key == 2 || key == 3 || key == 4) break; else { if (A.Top() == '(') { cout << "多左括号(" << endl; key = 5; } else if (A.Top() == '[') { cout << "多左括号[" << endl; key = 6; } A.Pop(); } } } switch (key) { case 0: cout << " " << endl; break; case 1: cout << "多右括号)" << endl; break; case 2: cout << "[和)不匹配" << endl; break; case 3: cout << "多右括号]" << endl; break; case 4: cout << "(和]不匹配" << endl; break; case 5: cout << "" ; break; case 6: cout << "" ; break; default: break; } }
标签:匹配,SqStack,int,char,括号,length,base,Push 来源: https://www.cnblogs.com/sheep-mr/p/16388248.html