数据结构趣题——括号匹配

   1: #include <stdio.h>
   2: #include <stdlib.h>
   3: #define STACK_INIT_SIZE 20
   4: #define STACKINCREMENT 10
   5:  
   6: typedef char ElemType;   /*将char类型定义为ElemType*/
   7:  
   8: typedef struct{        /*定义一个栈类型*/
   9:     ElemType *base;
  10:     ElemType *top;
  11:     int stacksize;
  12: }sqStack;
  13:  
  14:  
  15: void initStack(sqStack *s)
  16: {
  17:     /*内存中开辟一段连续空间作为栈空间,首地址赋值给s->base*/
  18:     s->base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
  19:     if(!s->base) exit(0);     /*分配空间失败*/
  20:     s->top = s->base;       /*最开始,栈顶就是栈底*/
  21:     s->stacksize = STACK_INIT_SIZE;   /*最大容量为STACK_INIT_SIZE */
  22: }
  23:  
  24: void Push(sqStack *s, ElemType e){        /*入栈操作*/
  25:     if(s->top - s->base >= s->stacksize){
  26:     /*栈满,追加空间*/
  27:     s->base = (ElemType *)realloc(s->base, (s->stacksize +
  28:     STACKINCREMENT)*sizeof(ElemType));
  29:     if(!s->base) exit(0);   /*存储分配失败*/
  30:     s->top = s->base + s->stacksize;
  31:     s->stacksize = s->stacksize + STACKINCREMENT; /*设置栈的最大容量*/
  32:     }
  33:     *(s->top) = e;  /*放入数据*/
  34:         s->top++;
  35: }
  36:  
  37: void Pop(sqStack *s , ElemType *e){   /*出栈操作*/
  38:     if(s->top == s->base) return;  /*将栈顶元素弹出*/
  39:     *e = *--(s->top);              /*修改栈顶指针*/
  40: }
  41:  
  42: int StackLen(sqStack s){     /*获得栈s的大小*/
  43:     return (s.top - s.base) ;
  44: }
  45:  
  46:  
  47: int match(char e,char c){
  48:     if(e=='(' && c==')')return 1;
  49:     if(e=='[' && c==']')return 1;
  50:     return 0;
  51: }
  52:  
  53: int main()
  54: {
  55:     sqStack s;
  56:     char c , e ;
  57:     initStack( &s ) ;  /*初始化一个空栈*/
  58:     scanf("%c",&c);  /*输入第一个字符*/
  59:     while(c!='#'){   /*'#'为输入的结束标志*/
  60:         if(!StackLen(s))
  61:             Push(&s,c);  /*如果栈为空,则说明输入的是第一个字符,因此保存在栈中*/
  62:         else
  63:         {
  64:              Pop(&s,&e);    /*取出栈顶元素*/
  65:              if(!match(e,c)){  /*将输入的元素与取出的栈顶进行比较,如果匹配不成功*/
  66:                 Push(&s,e);   /*先将原栈顶元素重新入栈*/
  67:                 Push(&s,c);   /*再将输入的括号字符入栈*/
  68:                }
  69:         }
  70:         scanf("%c",&c);  /*输入下一个字符*/
  71:         }
  72:     if(!StackLen(s))  printf("The brackets are matched\n");  /*如果栈s为空,则括号完全匹配*/
  73:     else  printf("The brackets are not matched\n");   /*如果栈s不为空,则括号不完全匹配*/
  74:     return 0;
  75:  
  76: }
  77:  

你可能感兴趣的:(数据结构)