7-5 PARENTHESIS.C
1#include <stdio.h>2 #defineMAXLENGTH 80//Maximum string length3 #defineStack_init_size 1004 #defineSize_increment 55typedefstruct //Stack Structure6 {7 int*Base;//Bottom of Stack8 int*top;//Top of Stack9 intStackSize//Stack sizeTen}sqstack,*Sqstack; One intStackinit (Sqstack s)//Initialize Stack A { -S->Base=(int*)malloc(stack_init_size*sizeof(int)); - if(! (s->Base)) theExit0); -S->top=s->Base; -S->stacksize=stack_init_size; - return 1; + } - intPUSH (Sqstack S,intE//into the stack + { A if(s->Base+s->stacksize==s->top) at { -S->Base=(int*)realloc(s->Base, (size_increment+s->stacksize) *sizeof(int)); -S->top=s->Base+s->stacksize; -s->stacksize+=size_increment; - } -* (s->top) =e; ins->top+=1; - return 1; to } + intPOP (Sqstack S,int*P)//out of the stack - { the if(s->Base==s->top)//Empty Stack * return 0; $*p=* (s->top-1);Panax Notoginsengs->top--; - return 1; the } + intStacklength (Sqstack s)//length of stack (number of elements) A { the return(s->top-s->Base); + } - intStackfree (Sqstack s)//Release Stack $ { $ Free(s->Base); -S->top=s->Base=NULL; - return 1; the } - Wuyi voidParenthesismatch (Char*expr) the { - Sqstack S; Wu intI,len,no; - if(! Stackinit (&s))//failed to initialize stack AboutExit0);//Exit $Len=strlen (expr);//Take string length - for(i=1; i<=len;i++) - { - if(expr[i-1]=='(') APUSH (&s,i);//left interpolation position sequence number into the stack + Else if(expr[i-1]==')') the { - if(POP (&s,&no)) $printf"pair of brackets:%d--%d\n", no,i); the Else theprintf"there is no opening parenthesis paired with the right number at location%d!\n", i); the } the } - while(Stacklength (&s) >0)//If there is data in the stack, it means that the left parenthesis is not paired. in { thePOP (&s,&no); theprintf"the opening parenthesis at position%d does not have a paired closing parenthesis!\n", no); About } theStackfree (&s);//Release Stack the } the intMain () + { - CharExpr[maxlength]; theprintf"Enter an expression with parentheses (not exceeding%d characters): \ n", MAXLENGTH); Bayiscanf"%s", expr); the Parenthesismatch (expr); the - getch (); - return 0; the}
7.4 Bracket Matching