資料結構習題——7表示式括號匹配
阿新 • • 發佈:2019-01-08
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; }