棧的應用(括號匹配問題)

括號匹配問題是一種典型的棧思想的應用。利用棧先進後出原則,使得最裏面的括號最先匹配,一次出棧匹配到最外面。代碼如下:

#include <iostream>
#include <stdio.h>
#define MaxSize 10
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

/**
棧的應用,括號的匹配問題。 
*/

//定義一個靜態方式的棧 
typedef struct{
    char data[MaxSize];//靜態數組存放棧元素 
    int top;//棧頂指針 
}Stack; 

//初始化棧 
void InitStack(Stack &S){
    S.top = -1;
}

//判斷棧是否空
bool isEmpty(Stack &S){
    if(S.top==-1){
        return true;
    }else{
        return false;
    }
} 

//入棧
bool PushStack(Stack &S,char x){
    if(S.top==MaxSize-1){//棧滿報錯 
        return false;
    }//top指針先指向最新的棧頂元素 
    S.data[++S.top] = x;//將值賦給棧頂元素 
    return true;
} 

//出棧(x返回)
bool PopStack(Stack &S,char &x){
    if(S.top = -1){//棧空報錯 
        return false;
    }
    x = S.data[--S.top];
    return true;
}  

//括號匹配
bool StackMatch(char str[],int length){
    Stack S;//聲明棧
    InitStack(S);//初始化棧
    for(int i=0;i<length;i++){
        if(str[i]=='(' || str[i]=='[' || str[i]=='{'){
            PushStack(S,str[i]);//掃描到左括號入棧 
        }else{
            if(isEmpty(S)){
                return false;
            }
            char topElem;
            PopStack(S,topElem);//棧頂元素出棧 
            if(str[i]=='(' && topElem!=')'){
                return false;
            }
            if(str[i]=='[' && topElem!=']'){
                return false;
            }
            if(str[i]=='{' && topElem!='}'){
                return false;
            }
        }   
    }
    return isEmpty(S);//棧空說明匹配成功 
} 

int main(int argc, char** argv) {
    char str[] = {'('};
    char str1[] = {'(',')'};
    char str2[] = {'(','(','(',')',')'};
    char str3[] = {'(','(',')',')',')'};
    char str4[] = {')'};

    /*
    printf("您要匹配的括號元素是:");
    for(int i=0;i<5;i++){
        printf("%c",str2[i]);
    }
    */

    bool flag = StackMatch(str2,5); 
    printf("\nflag=%d",flag);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章