码迷,mamicode.com
首页 > 其他好文 > 详细

括号匹配问题(顺序栈实现)

时间:2016-10-14 23:39:04      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

本周老师作业留了两个。先上传一个吧。那个有时间我再传上来~

本周的要求:

1.给出顺序栈的存储结构定义。
2.完成顺序栈的基本操作函数。
1)      初始化顺序栈
2)      实现入栈和出栈操作
3)      实现取栈顶元素和判空操作
括号匹配问题
3.编写主函数实现基本操作函数功能,并设置测试数据,测试合法和非法数据的输出结果。
4.程序调试运行并保存输出结果。
5.整理并提交实验作业。
  1 #include <cstdio>
  2 #include <cstring>
  3 #define Stack_Size 50
  4 
  5 typedef struct 
  6 {
  7     char a[Stack_Size];
  8     int top;
  9 }SeqStack;
 10 
 11 int IsEmpty(SeqStack *S)//栈判空
 12 {
 13     return S->top == -1;
 14 }
 15 
 16 int Match(char ch1,char ch2)//字符串匹配
 17 {
 18     switch(ch2){
 19     case ):
 20         if(ch1==()
 21             return 1;
 22         break;
 23     case }:
 24         if(ch1=={)
 25             return 1;
 26         break;
 27     case ]:
 28         if(ch1==[)
 29             return 1;
 30         break;
 31     }
 32     return 0;
 33 }
 34 
 35 void InitStack(SeqStack * S)//初始化顺序栈
 36 {
 37     S->top = -1;
 38 }
 39 
 40 void Push(SeqStack * S,char x)//进栈
 41 {
 42     S->top++;
 43     S->a[S->top]=x;
 44 }
 45 
 46 void Pop(SeqStack * S,char *x)//出栈
 47 {
 48     *x=S->a[S->top];
 49     S->top--;
 50 }
 51 
 52 void GetTop(SeqStack * S,char *x)
 53 {
 54     *x=S->a[S->top]; 
 55 }
 56 
 57 
 58 void BracketMatch(char *str)
 59 {
 60     SeqStack S;
 61     char ch;
 62     InitStack(&S);
 63     for(int i=0;str[i]!=\0;i++)
 64     {
 65         switch(str[i]){
 66         case (:
 67         case[:
 68         case{:
 69             Push(&S,str[i]);
 70             break;
 71         case ):
 72         case]:
 73         case}:
 74             if(IsEmpty(&S)){
 75                 printf("\n右括号多余!\n");
 76                 return ;
 77             }
 78             else{
 79                 GetTop(&S,&ch);
 80                 if(Match(ch,str[i]))
 81                     Pop(&S,&ch);
 82                 else{
 83                     printf("\n 对应的左右括号不同类!\n");
 84                     return ;
 85                 }
 86             }
 87 
 88         }
 89     }
 90     if(IsEmpty(&S))
 91         printf("\n括号匹配!\n");
 92     else
 93         printf("\n左括号多余!\n");
 94 }
 95 
 96 
 97 int main()
 98 {
 99     char strr[50];
100     printf("请输入各种括号\n");
101     gets(strr);
102     BracketMatch(strr);
103 
104     return 0;
105 }

括号匹配问题(顺序栈实现)

标签:

原文地址:http://www.cnblogs.com/xzt6/p/5962306.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!