首页 > 代码库 > [栈和队列]括号匹配

[栈和队列]括号匹配

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #define INIT_STACK_SIZE 100
 5 typedef struct
 6 {
 7     char * chOperator;
 8     int dwtop;
 9 }OPND;
10 
11 void InitStack(OPND *);
12 char Pop(OPND *);
13 void Push(OPND *,char );
14 char GetTop(OPND);
15 void printStack(OPND);
16 
17 char stringBuffer[128] = {\0};
18 int main()
19 {
20     OPND opnd;
21     int length,flag = 0;
22     char ch,*pch;
23 
24     InitStack(&opnd);
25     Push(&opnd,#);
26 
27     gets(stringBuffer);
28     pch = stringBuffer;
29 
30     length = strlen(stringBuffer);
31     while(length -- )
32     {
33         ch = *pch++;
34         if((ch == () ||(ch == [))           Push(&opnd,ch);
35         else if(ch == ))
36               {
37                 if(GetTop(opnd) == ()         Pop(&opnd);
38                 else flag = 1;
39               }
40               else if(ch == ])
41                    {
42                      if(GetTop(opnd) == [)    Pop(&opnd);
43                      else flag = 1;
44                     }
45     }
46     if(flag || (GetTop(opnd) != #)) printf("Match false!\n");
47     else printf("Match succeed!\n");
48 
49     return 0;
50 }
51 void InitStack(OPND *S)
52 {
53     S->chOperator = (char *)malloc(INIT_STACK_SIZE * sizeof(char));
54     if(!S->chOperator) exit(1);
55     S->dwtop = 0;
56 }
57 void Push(OPND *S,char ch)
58 {
59     *(S->chOperator + S->dwtop) = ch;
60     S->dwtop++;
61 }
62 char Pop(OPND *S)
63 {
64     S->dwtop--;
65     return *(S->chOperator + S->dwtop);
66 }
67 void printStack(OPND opnd)
68 {
69     while(opnd.dwtop){
70         opnd.dwtop--;
71         printf("%c",*(opnd.chOperator + opnd.dwtop));
72     }
73 }
74 char GetTop(OPND opnd)
75 {
76     return *(opnd.chOperator + opnd.dwtop -1);
77 }