欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

栈的应用——括号匹配

程序员文章站 2022-07-14 23:13:24
...
// A code block

 1. 遇到左括号入栈
 2. 遇到右括号,出栈,如果与当前的右括号匹配则当前匹配成功,否则失败
 3. 遍历目标要匹配字符串,并重复1,2步骤

// An highlighted block
/*
栈的应用------括号匹配
*/
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 60
struct Stack
{
    char data[MAXSIZE];
    int top;
    /* data */
};
void CreateStack(Stack &s){
    s.top = -1;
}
int IsEmpty(Stack &s){
    if(s.top == -1)
        return 1;
    else
        return 0;
}
int Push(Stack &s,char data){
    if(s.top==MAXSIZE-1)
        return 0;
    s.data[++s.top] = data;
    return 1;
}
int Pop(Stack &s,char &data){
    if(s.top == -1)
        return 0;
    data = s.data[s.top--];
    return 1;
}
int Testify(Stack &s,char data[],int length){

    char res;
    for(int i=0;i<length;i++){

        switch (data[i])
        {
            case '[':
                Push(s,data[i]);
                break;
            case '(':
                Push(s,data[i]);
                break;
            case '{':
                Push(s,data[i]);
                break;
            case ']':
                Pop(s,res);
                if(res != '[')
                    return 0;
                break;
            case '}':
                Pop(s,res);
                if(res != '{')
                    return 0;
                break;
            case ')':
                Pop(s,res);
                if(res != '(')
                    return 0;
                break;
            default:
                break;
        }
    }
    return IsEmpty(s);
}
int GetLength(char data[]){

    int i;
    for(i=0;data[i];i++);
    return i;
}
int main(){

    Stack s;
    char data[] = {"(({[]()}))"};
    int length = 0;
    CreateStack(s);
    length = GetLength(data);
    int result = 0;
    result = Testify(s,data,length);
    if(result == 1){
        printf("SUCCESS!\n");
    }else{
        printf("FAILED!\n");
    }
    system("pause");
    return 1;
}
/*
    测试:              答案:
        (((])){()})         FAILED
        (([]))[[]]          SUCCESS
        (({[]()}))          SUCCESS
        (()){[]}]           FAILED
*/