数据结构-括号匹配程序

程序代码如下:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #define STACK_INIT_SIZE 100
 4 #define STACKINCREMENT 10
 5 #define OVERFLOW -2
 6 #define OK 1
 7 #define ERROR 0
 8 
 9 typedef char SElemType;
10 
11 //栈结构体
12 typedef struct {
13     SElemType *base;
14     SElemType *top;
15     int stacksize;
16 }SqStack;
17 
18 int InitStack(SqStack *S);//初始化栈
19 int Push(SqStack *S,SElemType e);//入栈
20 int Pop(SqStack *S,SElemType *e);//删除栈中的元素
21 int DestoryStack(SqStack *S);//销毁栈
22 
23 //初始化栈
24 int InitStack(SqStack *S) {
25     S->base = (SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
26     if(!S->base) {
27         exit(OVERFLOW);
28     }
29     S->top = S->base;
30     S->stacksize = STACK_INIT_SIZE;
31 
32     return OK;
33 }
34 
35 //入栈
36 int Push(SqStack *S,SElemType e) {
37     if((S->top-S->base)>=S->stacksize) {
38         S->base = (SElemType*)realloc(S->base,(S->stacksize+STACKINCREMENT)*sizeof(SElemType));
39         if(!S->base) exit(OVERFLOW);
40         S->top = S->base + S->stacksize;
41         S->stacksize += STACKINCREMENT;
42     }
43     *S->top++ = e;
44     return OK;
45 }
46 
47 //删除栈中的元素
48 int Pop(SqStack *S,SElemType *e) {
49     if(S->top  == S->base) return ERROR;
50     *e = *--S->top;
51     return OK;
52 }
53 
54 //销毁栈
55 int DestoryStack(SqStack *S) {
56     S->top = S->base;
57     free(S->base);
58     S->top = NULL;
59     S->base = NULL;
60     return OK;
61 }
62 
63 //进行括号匹配
64 int Match(SqStack *S) {
65     char ch,c;
66     printf("请输入待匹配的括号:");
67     ch = getchar();
68     while(ch != '
') {
69         if(ch=='('||ch=='[') {
70             Push(S,ch);
71         }
72         if(ch==')') {
73             Pop(S,&c);
74             if(c!='(') {
75                 return ERROR;
76             }
77         }
78         if(ch==']') {
79             Pop(S,&c);
80             if(c!='[') {
81                 return ERROR;
82             }
83         }
84         ch = getchar();
85     }
86     return OK;
87 }
88 
89 int main()
90 {
91     SqStack sq;
92     int f;
93     InitStack(&sq);
94     f = Match(&sq);//进行括号匹配检验
95     if(f) printf("括号全部匹配!
");
96     else printf("括号匹配失败!
");
97     DestoryStack(&sq);//将栈销毁
98     return 0;
99 }
原文地址:https://www.cnblogs.com/chengzi123/p/4370141.html