栈——匹配()[]

 

 

//"SqStack.h"
#include<iostream>
using namespace std;

#define SElemType int
#define MAXSIZE 100

typedef struct{
    SElemType *base;
    SElemType *top;
    int stacksize;
}SqStack;

string InitStack(SqStack &S){
    S.base = new SElemType[MAXSIZE];
    S.top = S.base;
    S.stacksize=MAXSIZE;
    return "OK";
}

string Push(SqStack &S,SElemType e){
    if(S.top-S.base == S.stacksize) return "ERROR";
    *S.top=e;
    S.top++;
    return "OK";
}

string pop(SqStack &S,SElemType &e){
    if(S.base == S.top) return "ERROE";
    S.top--;
    e = *S.top;
    return "OK";
}

SElemType GetTop(SqStack S){
    if(S.top != S.base){
        return *(S.top-1);
    }
} 

int StackEmpty(SqStack S){
    if(S.top == S.base) return 1;
    return 0;
}

 

#include<iostream>
using namespace std;
#include"SqStack.h"
/*
   匹配()[]
*/
int main(){

    SqStack S;
    InitStack(S);
    int flag = 1;       //1表示匹配正确,0表示错误

    char ch;
    cin >> ch;
    while(ch != '!' && flag){
        
        switch (ch)
        {
        case '[':
            Push(S,1);
            
            break;
        case '(':
            Push(S,2);
            
            break;
        
        case ')':
            if(!StackEmpty(S) && GetTop(S) == 2){
                SElemType x;
                pop(S,x);
            }else
            {
                
                flag = 0;
            }
            break;
        
        case ']':
            if(!StackEmpty(S) && GetTop(S) == 1){
                SElemType x;
                pop(S,x);
            }else
            {
                
                flag = 0;
            }
            break;
        }
        cin >> ch;
    }
    // cout << StackEmpty(S)<<" "<<flag;
    if(StackEmpty(S) && flag) cout <<"true";
    else
    {
        cout << "WRONG";
    }
    
    system("pause");
    return 0;
}

 

posted @ 2020-11-18 23:11  倔强的不死人  阅读(121)  评论(0编辑  收藏  举报