/*Detect balance Symbols*/#include<stdio.h>#include<stdlib.h>structStack;typedefstructStack *Ptrtostack;structstack{Char*Array; intTopofstack; intcapacity;}; Ptrtostackcreatestack (intMaxSize) {Ptrtostack p; P=malloc(sizeof(structstack)); P->array =malloc(sizeof(Char) *MaxSize); P->capacity =MaxSize; P->topofstack =-1; returnp;}intIsEmpty (Ptrtostack s) {returnS->topofstack = =-1;}voidPop (Ptrtostack s) {if( !IsEmpty (s)) s->topofstack--; Elseprintf ("Error");}CharTop (Ptrtostack s) {if( !IsEmpty (s))returnS->array[s->Topofstack]; Elseprintf ("Error");}intIsfull (Ptrtostack s) {returnS->topofstack = = s->capacity-1;}voidPush (Charch, ptrtostack s) { if( !Isfull (s)) s->array[++s->topofstack] =ch; Elseprintf ("Error");}//encountered open symbol stack empty, encountered open symbol mismatch, read in completed, stack is not emptyintMain () {intMaxSize =Ten; Chartmp; Ptrtostack s; S=Createstack (MaxSize); while(TMP = GetChar ())! ='#' ) { if(TMP = ='('|| TMP = ='{'|| TMP = ='[') Push (TMP, s); Else { if(IsEmpty (s)) {printf ("Error1"); return 0; } Else { Switch(TMP) { Case ']': if(Top (s)! ='[') {printf ("Error2"); return 0; } Break; Case ')': if(Top (s)! ='(') {printf ("Error2"); return 0; } Break; Case '}': if(Top (s)! ='{') {printf ("Error2"); return 0; } Break; }//SwitchPop (s); }//Else}//Else}// while if(S->topofstack! =-1) {printf ("Error3"); return 0; }}
View Code
Note that the algorithm is 3 error:1. When you read a closed symbol, the stack is empty Error1
2. Read # stack non-empty Error2
3. Read the closed symbol, the stack is not empty, but does not correspond to Error3
Exercise 3.18 Detecting the balance symbol (/* */do not know what to do)