數據結構習題——7表達式括號匹配

time_limit

3000MS

memory_limit

10000KB

description

假設一個算術表達式中可以包含三種括號:圓括號“(”和“)”、方括號“[”和“]”和花括號“{”和“}”,且這三種括號可按任意的次序嵌套使用(如:…[…{…}…[…]…]…[…]…(…)…)。編寫判別給定表達式中所含括號是否正確配對出現的程序(已知表達式已存入數據元素爲字符的順序表中)。

input

輸入算術表達式,換行結束。

output

若給定表達式中所含括號正確配對,則輸出yes,否則輸出no。

sample_input

[5+(6-3)]-(2+3)]

sample_output

no

#include <stdio.h>
#include <stdlib.h>
typedef int Elemtype;
#define N 200
typedef struct Stack{
    Elemtype elem[N];
    int top;
}SeqStack,*PSeqStack;

PSeqStack Init_stack()
{
    PSeqStack pstack;
    pstack=(PSeqStack)malloc(sizeof(SeqStack));
    if(pstack==NULL)printf("Out of space!\n");
    else pstack->top=-1;
    return pstack;
}

void push(PSeqStack pstack,Elemtype x)
{
    if(pstack->top>=N-1)printf("Overflow!");
    else{
		pstack->top++;
        pstack->elem[pstack->top]=x;
    }
}
int isnull(PSeqStack pstack)
{
    return (pstack->top==-1);
}
Elemtype pop(PSeqStack pstack)
{
    Elemtype x;
    x=pstack->elem[pstack->top];
    pstack->top--;
    return x;
}
Elemtype get(PSeqStack pstack)
{
    Elemtype x;
    x=pstack->elem[pstack->top];
    return x;
}
int main()
{
    char s[100],t;
    int i=0;
    PSeqStack pstack;
    pstack=Init_stack();
    gets(s);
    while(s[i]!='\0'){
        if(s[i]==')'||s[i]==']'||s[i]=='}'||s[i]=='('||s[i]=='['||s[i]=='{'){
            if(s[i]=='('||s[i]=='['||s[i]=='{')
                push(pstack,s[i]);
            else{
                if(isnull(pstack)){printf("no\n");break;}
                t=get(pstack);
                if(s[i]==t+1||s[i]==t+2){
                    pop(pstack);
                }
                else {printf("no\n");break;}
            }
        }
        i++;
    }
    if(s[i]=='\0'&&isnull(pstack))printf("yes\n");
    //printf("Hello world!\n");
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章