括号匹配检验(栈)
示例:
eg1: {[(1+2)3+6]-29}*2-4
左右括号匹配
eg2: ( {[(1+2)3+6]-29}*2-4
左括号多余
eg3: ){[(1+2)3+6]-29}*2-4
右括号多余
eg4:(]{[(1+2)3+6]-29}*2-4
左右括号不匹配
运行结果如下:
![]() |
![]() |
![]() |
![]() |
源代码如下:
#include<iostream>
#include<string>
using namespace std;
class Node {
public:
char ch;
Node* next;
Node(char c,Node *n=NULL):ch(c),next(n){}
Node():next(NULL){}
};
class Stack{
public:
Stack():top(NULL){}
~Stack() { while (top != NULL) { Node* temp = top; top = top->next; delete temp; } }
char gettop() { return top->ch; }
bool Empty() { return top == NULL; }
void push(char c);
void pop(char& c);
private:
Node* top;
};
void Stack::push(char c) {
if (top == NULL) { top = new Node(c); return; }
Node* p = new Node(c,top);
top = p;
}
void Stack::pop(char &c) {
if (top == NULL) return;
Node* p = top;
top = top->next;
c = p->ch;
delete p;
}
void check(string &s){
int n = s.size();
Stack stack;
for (int i = 0; i < n; i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') stack.push(s[i]);
if (s[i] == ')' || s[i] == ']' || s[i] == '}') {
if(stack.Empty()) {cout<<"右括号多余"<<endl;return;}
char ch = stack.gettop();
if (s[i] == ')' && ch == '(') stack.pop(ch);
else if (s[i] == ']' && ch == '[') stack.pop(ch);
else if (s[i] == '}' && ch == '{') stack.pop(ch);
else {cout<<"左右括号不匹配"<<endl;return;}
}
}
if (stack.Empty()) cout << "括号匹配" << endl;
else cout << "左括号多余" << endl;
}
int main() {
string s("(][(1+2)*3+6]-2*9}*2-4");//待检验算术表达式s
cout<<s<<endl;
check(s);
return 0;
}