数据结构课程设计(括号匹配的检验) #include <stdio.h> #include <stdlib.h> #define MAXSIZE 100 typedef char SElemType; #define OK 0 #define ERROR 1 #define OVERFLOW -2 typedef int Status; typedef struct { SElemType *base; SElemType *top; Status stacksize; }SqStack; Status InitStack(SqStack* S) { S->base =(char*)malloc(sizeof(SElemType) * MAXSIZE); if( !S->base ) return OVERFLOW; S->top = S->base; S->stacksize = MAXSIZE; return OK; } Status StackLength( SqStack S ) { return S.top – S.base; } Status Push( SqStack* S, SElemType e) { if( S->top – S->base== S->stacksize ) return ERROR; *S->top++=e; return OK; } SElemType Pop( SqStack* S, SElemType e) { if( S->top == S->base ) { return ‘w’; } e=*–S->top; return e; } Status DestroyStack( SqStack* S ) { if( S->base ) { free(S->base); S->stacksize = 0; S->base = S->top = NULL; } return OK; } Status isLeft(char c) { Status ret = 0; switch(c) { case ‘(‘: case ‘[‘: case ‘<‘: case ‘{‘: case ”’: case ‘”‘: ret = 1; break; default: ret = 0; break; } return ret; } Status isRight(char c) { Status ret = 0; switch(c) { case ‘)’: case ‘]’: case ‘>’: case ‘}’: case ”’: case ‘”‘: ret = 1; break; default: ret = 0; break; } return ret; } Status match(char left, char right) { Status ret = 0; switch(left) { case ‘(‘: ret = (right == ‘)’); break; case ‘[‘: ret = (right == ‘]’); break; case ‘<‘: ret = (right == ‘>’); break; case ‘{‘: ret = (right == ‘}’); break; case ”’: ret = (right == ”’); break; case ‘”‘: ret = (right == ‘”‘); break; default: ret = 0; break; } return ret; } Status judge(const char* code) { SqStack stack; InitStack(&stack); Status ret=0; Status i=0; while( code[i] != ‘0’) { if(isLeft(code[i])) { Push(&stack,code[i]); } else if(isRight(code[i])) { char c = Pop(&stack,*(stack.top)); if(c==’w’ || !match(c,code[i])) { printf(“%c 匹配失败! ”,code[i]); break; } } i++; } if((StackLength(stack)==0)&&(code[i]==’0′)) { printf(“成功! ”); ret = 1; } else if((StackLength(stack)!=0)) { printf(“左括号有多余,匹配失败 ”); ret = 0; } DestroyStack(&stack); return ret; } void main() { char* str = (char*)malloc(sizeof(char)*MAXSIZE) ; scanf(“%s”,str); judge(str); free(str); }
2024最新激活全家桶教程,稳定运行到2099年,请移步至置顶文章:https://sigusoft.com/99576.html
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。 文章由激活谷谷主-小谷整理,转载请注明出处:https://sigusoft.com/52562.html