使用栈实现括号匹配

实现

栈的实现请参考:https://blog.csdn.net/u010837612/article/details/79914935

#include <iostream>
#include <stdlib.h>
#include "MyStack.h"

using namespace std;

int main(void) {

    char str[] = "[()]";

    char curNeed = 0;

    MyStack<char> *pStack = new MyStack<char>(20);

    for (int i = 0; i < strlen(str); i++) {
        //如果栈为空,或者当前字符是左括号,则入栈
        if (pStack->isEmpty() || str[i] == '(' || str[i] == '[') {
            pStack->push(str[i]);
        }
        else {

            char top;
            //将栈顶弹出,如果当前字符与之不匹配,则将弹出的元素入栈,当前字符也入栈
            if (pStack->pop(top)) {
                switch (top)
                {
                case '(':curNeed = ')'; break;
                case '[':curNeed = ']'; break;
                }
                if (str[i] != curNeed) {
                    pStack->push(top);
                    pStack->push(str[i]);
                }
            }
            curNeed = 0;
        }

    }
    if (pStack->isEmpty()) {
        cout << "匹配" << endl;
    }
    else {
        cout << "不匹配" << endl;
    }
    system("pause");
    return 0;

}

猜你喜欢

转载自blog.csdn.net/u010837612/article/details/79927485