symbols匹配问题
#include<iostream> #include<string> using namespace std; struct Node { char data; Node*next; }; struct LinkStack { Node*top; }; LinkStack*create() { LinkStack*stack = new LinkStack; stack->top = NULL; return stack; } bool isEmpty(LinkStack*stack) { return (stack->top == NULL); } void pop(LinkStack*stack) { Node*p = stack->top; stack->top = stack->top->next; delete p; } void push(LinkStack*stack, char item) { Node*p = new Node; p->data = item; p->next = stack->top; stack->top = p; } char Top(LinkStack*stack) { return stack->top->data; } int main() { string s; cin >> s; LinkStack*stack = create(); bool flag = true; for (auto i:s) { if (i == ‘(‘ || i == ‘[‘ || i == ‘{‘) push(stack, i); if (i == ‘)‘) { if (!isEmpty(stack)) { if (isEmpty(stack) && Top(stack) != ‘(‘) { flag = false; break; } else { pop(stack); } } else { flag = false; break; } } else if (i == ‘]‘) { if (!isEmpty(stack)) { if (isEmpty(stack) && Top(stack) != ‘[‘) { flag = false; break; } else { pop(stack); } } else { flag = false; break; } } else if (i == ‘}‘) { if (!isEmpty(stack)) { if (Top(stack) != ‘{‘) { flag = false; break; } else { pop(stack); } } else { flag = false; break; } } } if (!isEmpty(stack)) flag = false; else if (flag) cout << "MATCH" << endl; else cout << "ERROR"<<endl; delete stack; return 0; }
时间: 2024-10-18 15:03:27