[栈和队列]括号匹配

 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 }

 

 

转载于:https://www.cnblogs.com/wujichaomx/p/3702629.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值