括号匹配(栈)

 

二、思路

如果当前元素为[或者(则入栈,如果当前元素为]或者)则判断当前元素与栈顶元素是否匹配,如果匹配则出栈,如果不匹配则输出No。在最后应判断栈是否为空,若为空则整个匹配,若不为空则整个不匹配

三、代码

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define maxsize 100
using namespace std;

typedef struct {
    char data[maxsize];//元素
    int top;//栈头
}SqStack;

//栈空
bool stackEmpty(SqStack& list) {
    if (list.top == -1)
        return true;//栈空
    else return false;//栈不空
}

//入栈
bool push(SqStack& list, char element) {
    if (list.top==maxsize-1){
        return false;//栈满,不能入栈
    }
    else {
        list.top++;
        list.data[list.top] = element;
        return true;
    }
}
//出栈
bool pop(SqStack& list, char element) {
    if (list.top == -1) {
        return false;//栈空,不能出栈
    }
    else {
        element = list.data[list.top];
        list.top--;
        return true;
    }
}
//初始化
void initStack(SqStack& list) {
    list.top = -1;
}
//栈顶元素
bool getpop(SqStack s,char a) {
    if (s.top == -1)
        return false;
    else {
        a = s.data[s.top];
        return true;
    }
}
int main() {
    SqStack s;
    initStack(s);
    //输入字符串
    int num;
    cin >> num;
    char str[100] ="";
    for (int i = 0; i < num; i++) {
        char a = NULL;
        cin >> a;
        str[i] = a;
    }
    char* p = str;
    for(int i = 0; i < num;i++) {
        if (*p == '[' || *p == '(') {
            push(s, *p);
            p++;
        }
        else {
            char getpop1 = NULL;
            getpop(s, getpop1);
            if (getpop1 == '[' && *p == ']' || getpop1 == '(' && *p == ')') {
                char pop1=NULL;
                pop(s, pop1);
                p++;
            }
            else
                cout << "NO" << endl;
        }
    }
    if (stackEmpty(s))
    {
        cout << "Yes" << endl;
    }
    else cout << "No" << endl;
}
View Code

 

posted @ 2022-03-01 20:06  Protect_Winter  阅读(38)  评论(0)    收藏  举报