数据结构之SeqStack---堆栈应用---括号匹配问题

SeqStack.h

#include “stdio.h” #include “math.h” typedef struct { DataType stack [MaxStackSize]; int top; } SeqStack; void StackInitiate(SeqStack *S) { S->top = 0; } int StackNotEmpty(SeqStack *S) { if (S->top <= 0) { return 0; } else { return 1; } } int StackPush(SeqStack * S,DataType d) { if (S->top >= MaxStackSize) { printf(“堆栈已满无法插入!/n”); return 0; } else { //这时候S->top刚好为空待插入,因为数组从0开始 S->stack [S->top] = d; S->top++; return 1; } } int StackPop(SeqStack * S, DataType *d) { if ( S->top <= 0) { printf(“堆栈已经空无需出栈!/n”); return 0; } else { //记住顺序,因为数组是从0开始的 S->top–; *d = S->stack [S->top]; return 1; } } int StackTop(SeqStack * S, DataType *d) { if ( S->top <= 0) { printf(“堆栈已经空,没有数可以取出!/n”); return 0; } else { *d = S->stack [S->top-1]; return 1; } }

 

kuohao.cpp

#include “stdio.h” #include “stdlib.h” #include “string.h” #define MaxStackSize 100 typedef char DataType; #include “SeqStack.h” void ExpIsCorrect(char exp[], int n); void main() { char test1[] = “({[]f})}”; char test2[] = “(({}sdf[](df[])))”; ExpIsCorrect(test1, strlen(test1)); ExpIsCorrect(test2, strlen(test2)); char test[100]; while(scanf(“%s”,&test) != EOF) { ExpIsCorrect(test, strlen(test)); } } void ExpIsCorrect(char exp[], int n) { int i ; char x; SeqStack myStack; StackInitiate(&myStack); for (i = 0; i < n; i++) { if (exp[i] == ‘(‘ || exp[i] == ‘[‘ || exp[i] == ‘{‘) { StackPush(&myStack, exp[i]); } else if (exp[i] == ‘)’ && StackNotEmpty(&myStack) && StackTop(&myStack, &x) && x == ‘(‘) { StackPop(&myStack, &x); } else if (exp[i] == ‘)’ && StackNotEmpty(&myStack) && StackTop(&myStack, &x) && x != ‘(‘) { printf(“括号匹配不正确!/n”); return; } else if (exp[i] == ‘]’ && StackNotEmpty(&myStack) && StackTop(&myStack, &x) && x == ‘[‘) { StackPop(&myStack, &x); } else if (exp[i] == ‘]’ && StackNotEmpty(&myStack) && StackTop(&myStack, &x) && x != ‘[‘) { printf(“括号匹配不正确!/n”); return; } else if (exp[i] == ‘}’ && StackNotEmpty(&myStack) && StackTop(&myStack, &x) && x == ‘{‘) { StackPop(&myStack, &x); } else if (exp[i] == ‘}’ && StackNotEmpty(&myStack) && StackTop(&myStack, &x) && x != ‘{‘) { printf(“括号匹配不正确!/n”); return; } else if ( exp[i] == ‘)’ || exp[i] == ‘]’ || exp[i] == ‘}’ && !StackNotEmpty(&myStack) ) { printf(“右括号多于左括号!/n”); return; } } if (StackNotEmpty(&myStack)) { printf(“左括号多于右括号!/n”); } else { printf(“括号匹配正确!/n”); } }

 

 

    原文作者:括号匹配问题
    原文地址: https://blog.csdn.net/zhoulingjie311/article/details/6359259
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞