<span style="font-size:14px;">#ifndef LIST_H_INCLUDED #define LIST_H_INCLUDED /* * Copyright (c) 2015, 烟台大学计算机与控制工程学院 * All rights reserved. * 文件名称:main.cpp,hanshu.cpp,list.h * 作者:徐吉平 * 完成日期:2015年10月10日 * 版本号:code ::Block 13.12 * * 问题描述:假设表达式中允许三种括号:圆括号、方括号和大括号。编写一个算法,判断表达式中的各种左括号是否与右括号匹配。 例如,输入2+(3+4)*[2+{[3]}]-8,输出匹配正确;输入2+(3+4*[2)+{[3]}-8,输出匹配错误。 * 输入描述:无 * 程序输出:配对结果</span>
<span style="font-size:14px;">list.h #include <stdio.h> #include <malloc.h> typedef char ElemType; typedef struct linknode { ElemType data; //数据域 struct linknode *next; //指针域 } LiStack; //链栈类型定义 void InitStack(LiStack *&s); //初始化栈 void DestroyStack(LiStack *&s); //销毁栈 int StackLength(LiStack *s); //返回栈长度 bool StackEmpty(LiStack *s); //判断栈是否为空 void Push(LiStack *&s,ElemType e); //入栈 bool Pop(LiStack *&s,ElemType &e); //出栈 bool GetTop(LiStack *s,ElemType &e); //取栈顶元素 void DispStack(LiStack *s); //输出栈中元素 bool Match(char st[50]); #endif // LIST_H_INCLUDED */</span>hanshu.cpp
#include "list.h" bool Match(char *st) { char c; bool b=true; LiStack *s; InitStack(s); for(int i=0;st[i]!='\0'&&b;i++) { switch(st[i]) { case'(': case'[': case'{': Push(s,st[i]); break; case')': Pop(s,c); if(c!='(') { b=false; } break; case']': Pop(s,c); if(c!='[') { b=false; } break; case'}': Pop(s,c); if(c!='{') { b=false; } break; } } if(StackEmpty(s)&&b==true) { return true; } else { return false; } } /* int d=1; for(int i=0; st[i]!='\0'&&d; i++) { switch(st[i]) { case'(': case'[': case'{': Push(s, st[i]); break; case')': Pop(s, c); if(c!='(') d=0; break; case']': Pop(s, c); if(c!='[') d=0; break; case'}': Pop(s,c); if(c!='{') d=0; break; } } if(StackEmpty(s)&&d==1) return true; else return false; } */ void InitStack(LiStack *&s)//初始化栈 { s=(LiStack *)malloc(sizeof(LiStack)); s->next=NULL; } void DestroyStack(LiStack *&s) //销毁栈 { LiStack *p=s->next; while(p!=NULL) { free(s); s=p; p=p->next; } free(s); } bool StackEmpty(LiStack *s) //判断栈是否为空 { return(s->next==NULL); } void Push(LiStack *&s,ElemType e)//入栈 { LiStack *p; p=(LiStack *)malloc(sizeof(LiStack)); p->data=e; //新建元素e对应的节点*p p->next=s->next; //插入*p节点作为开始节点 s->next=p; } bool Pop(LiStack *&s,ElemType &e) //出栈 { LiStack *p; if(s->next==NULL) { return false; } p=s->next; e=p->data; s->next=p->next; free(p); return true; } bool GetTop(LiStack *s,ElemType &e) //取栈顶元素 { if (s->next==NULL) //栈空的情况 return false; e=s->next->data; return true; } void DispStack(LiStack *s) //输出栈中元素 { LiStack *p=s->next; while(p!=NULL) { printf("%c",p->data); p=p->next; } printf("\n"); } int StackLength(LiStack *s) //返回栈长度 { int i=0; LiStack *p; p=s->next; while (p!=NULL) { i++; p=p->next; } return(i); }
#include "list.h" int main() { char st[50]; printf("请输入表达式:"); scanf("%s", st); if(Match(st)) printf("配对正确!!\n"); else printf("配对错误!!\n"); return 0; }
总结:在本次项目函数的编写中,配对函数Match()我本来想用if else 语句编写,后来发现很复杂,就采用了贺老师采用的
switch(st[i])语句,这样就简单了许多,并在在语法做了稍微的改变,达到了理想的结果。