数据结构 栈应用(括号匹配检测)

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <math.h>
  4 
  5 #define OK    1
  6 #define ERROR 0
  7 #define STACK_INIT_SIZE 10
  8 #define STACKINCREMENT   2
  9 
 10 typedef int  Status;
 11 typedef char SElemType;
 12 
 13 typedef struct SqStack
 14 {
 15     SElemType *base;
 16     SElemType *top;
 17     int stacksize;
 18 }SqStack;
 19 
 20 Status InitStack(SqStack *S)
 21 {
 22     (*S).base = (SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
 23     if (!(*S).base)
 24         exit(OVERFLOW);
 25     (*S).top = (*S).base;
 26     (*S).stacksize = STACK_INIT_SIZE;
 27     return OK;
 28 }
 29 
 30 Status StackEmpty(SqStack S)
 31 {
 32     if (S.base == S.top)
 33         return OK;
 34     else
 35         return ERROR;
 36 }
 37 
 38 Status Push(SqStack *S,SElemType e)
 39 {
 40     if ((*S).top - (*S).base >= (*S).stacksize)
 41     {
 42         (*S).base = (SElemType *)realloc((*S).base,((*S).stacksize + STACKINCREMENT)*sizeof(SElemType));
 43         if (!(*S).base)
 44             exit(OVERFLOW);
 45         (*S).top = (*S).base + (*S).stacksize;
 46         (*S).stacksize +=STACKINCREMENT;
 47     }
 48     *((*S).top)++ = e;
 49     return OK;
 50 }
 51 
 52 Status Pop(SqStack *S,SElemType *e)
 53 {
 54     if ((*S).base == (*S).top)
 55         return ERROR;
 56     *e = *--(*S).top;
 57     return OK;
 58 }
 59 
 60 void main()
 61 {
 62     SqStack S;
 63     SElemType ch[100],*p,e;
 64     if(InitStack(&S))
 65     {
 66     
 67         printf("请输入表达式\n");
 68         gets(ch);
 69         p = ch;    
 70         while (*p)
 71             switch(*p)
 72             {
 73             case '(':
 74             case '[':Push(&S,*p++);
 75                      break;
 76             case ')':
 77             case ']':if(!StackEmpty(S))
 78                      {
 79                         Pop(&S,&e);
 80                         if(*p == ')' && e != '(' || *p == '[' && e != ']')
 81                         {
 82                             printf("左右括号不配对");
 83                             exit(OVERFLOW);
 84                         }
 85                         else
 86                         {
 87                             p++;
 88                             break;
 89                         }
 90                      }
 91                      else
 92                      {
 93                         printf("缺乏左括号!\n");
 94                         exit(ERROR);
 95                      }
 96             default : p++;
 97             }
 98         if(StackEmpty(S))
 99             printf("左右括号匹配!\n");
100         else 
101             printf("缺少右括号!\n");
102     }
103 }

 

 

posted on 2012-05-01 16:47  QLinux  阅读(842)  评论(0编辑  收藏  举报

导航