【程序练习】——括号匹配

  1 #include<stdio.h>
  2 #include<stdlib.h>
  3 #include<string.h>
  4 
  5 #define MAX 20
  6 
  7 
  8 typedef struct stack{
  9     char item;
 10     struct stack *next;
 11 }stack;
 12 
 13 char gettop_s(stack *h)            //得到栈顶元素
 14 {
 15     char ch;
 16     
 17     ch = h->item;
 18 
 19     return ch;
 20 }
 21 
 22 stack * out_s(stack *h)                //出栈
 23 {
 24     stack *p;
 25     char ch;
 26 
 27 
 28     p = h;
 29     ch = p->item;
 30     h = h->next;
 31 
 32     free(p);
 33 
 34     return h;
 35 }
 36 
 37 stack * insert_s(char ch, stack *h)                //入栈
 38 {
 39     stack *p;
 40 
 41     p = (stack *)malloc(sizeof(stack));
 42 
 43     p->item = ch;
 44     p->next = h;
 45 
 46     h = p;
 47 
 48     return h;
 49 }
 50 
 51 stack * init()                    //初始化栈
 52 {
 53     stack *h;
 54 
 55     h = (stack *)malloc(sizeof(stack));
 56 
 57     h->item = '\0';
 58     h->next = NULL;
 59      
 60     return h;
 61 }
 62 
 63 int cop_symbol(char a,char b)            //判断两个符号是否匹配
 64 {
 65     if(a == '[' && b == ']')
 66         return 1;
 67     else if(a == '(' && b == ')')
 68         return 1;
 69     else
 70         return 0;
 71 }
 72 
 73 int bracktext(char value[MAX], stack *h)                //括号检测
 74 {
 75     int i = 0;
 76     char topvalue;        //栈顶元素
 77 
 78     while(value[i] != '\0'){
 79     
 80         if(h->next == NULL)
 81             h = insert_s(value[i], h);
 82         else{
 83             topvalue = gettop_s(h);
 84             if(cop_symbol(topvalue, value[i]))
 85                 h = out_s(h);
 86             else
 87                 h = insert_s(value[i], h);
 88         }
 89         i++;
 90     }
 91 
 92     if(h->next != NULL)
 93         return 0;
 94     else
 95         return 1;
 96 
 97 }
 98 
 99 
100 int main()
101 {
102     stack *h;
103     int i = 0;
104     char textvalue[MAX];            //存放需要测试的值
105                             //栈头结点
106     puts("please enter some symbols you want to text");
107 
108     scanf("%s",textvalue);
109 
110     h = init();
111 
112     if(bracktext(textvalue, h))
113         printf("OK\n");
114     else
115         printf("NO\n");
116 
117 }

   进栈和出栈的时候要注意返回头指针,不然下次操作会找不到头结点。

posted @ 2013-09-26 11:16  net小伙  阅读(293)  评论(0编辑  收藏  举报