Page 156 - DCAP201_FUNDAMENTALS_OF_DATA_STRUCTURES
P. 156

Unit 9: Stacks




          int parenthesischecker(char str[])                                                    Notes
          {
          struct stack s;
          char ch;
          int i,flag=0;/*0 for no error, 1 for error*/
          s.top=-1;
          for(i=0;((str[i]!=’’) && (flag==0));i++)
          {if(str[i]==’(‘)
          push(&s,str[i]);
          else
          {ch=pop(&s);
          if(ch!=’(‘)
          flag=1;
          }
          }
          if(s.top!=-1)
          flag=1;
          return flag;
          }
          void main()
          {
          char str[MAX],flag;
          clrscr();
          printf(“nEnter a string of parenthesis?”);
          gets(str);
          flag=parenthesischecker(str);
          if(flag==0)
          {printf(“nParenthesis Match O.K.”);
          }
          else
          {printf(“nOpening/Closing Parenthesis do not match.”);
          }
          getch();
          }

          9.5.2 Evaluation of Arithmetic Expressions

          Stacks are useful in evaluation of arithmetic expressions. Consider the expression

          5 * 3 +2 + 6 * 4
          The expression can be evaluated by first multiplying 5 and 3, storing the result in A, adding
          2 and A, saving the result in A. We then multiply 6 and 4 and save the answer in B. We finish off
          by adding A and B and leaving the final answer in A.





                                           LOVELY PROFESSIONAL UNIVERSITY                                   149
   151   152   153   154   155   156   157   158   159   160   161