写出检验括号匹配的算法_写出检验括号匹配的算法是

写出检验括号匹配的算法_写出检验括号匹配的算法是数据结构—栈运用之括号匹配检验(LeetCode 20)好的,以下是实现括号匹配判别的 C 代码:“`c#include <stdio.h>#include <stdlib.h>

数据结构—栈运用之括号匹配检验(LeetCode 20)   好的,以下是实现括号匹配判别的 C 代码: “`c #include <stdio.h> #include <stdlib.h> #define STACK_SIZE 100 //栈空间大小 // 定义一个栈结构体 typedef struct { int top; // 栈顶指针 char s[STACK_SIZE]; // 栈空间 } Stack; // 初始化栈 void init(Stack *st){ st->top = -1; } // 入栈 void push(Stack *st, char c){ if (st->top == STACK_SIZE – 1){ printf(“栈已满,无法再入栈!   ”); exit(1); //程序异常退出 } st->top ++; st->s[st->top] = c; } // 出栈 char pop(Stack *st){ if (st->top < 0){ printf(“栈已空,无法出栈!   ”); exit(1); //程序异常退出 } char c = st->s[st->top]; st->top –; return c; } // 用于判断括号是否匹配的函数 int isMatch(char left, char right){ if (left == ‘(‘ && right == ‘)’) return 1; else if (left == ‘[‘ && right == ‘]’) return 1; else if (left == ‘{‘ && right == ‘}’) return 1; else return 0; } // 判断算术表达式中的括号是否匹配 int isParenthesesMatching(char *exp){ Stack st; init(&st); int i = 0; while (exp[i] != ‘0’){ if (exp[i] == ‘(‘ || exp[i] == ‘[‘ || exp[i] == ‘{‘){ push(&st, exp[i]); } else if (exp[i] == ‘)’ || exp[i] == ‘]’ || exp[i] == ‘}’){ if (st.top == -1 || !isMatch(pop(&st), exp[i])){ return 0; } } i ++; } if (st.top == -1){ return 1; } else{ return 0; } } int main(){ char exp[] = “2 * (3 + 5) – 10 / (4 – 2)]”; if (isParenthesesMatching(exp)){ printf(“表达式中的括号匹配!   ”); } else{ printf(“表达式中的括号不匹配!   ”); } return 0; } “` 上述代码的主要思路是:使用栈数据结构来存储左括号,当遇到右括号时,取出栈顶素与之匹配,若匹配则继续遍历,反之说明括号不匹配,返回0. 在遍历完整个表达式后,如果栈为空,则说明所有的括号都已匹配,返回1,反之说明有多余的左括号未被匹配,返回0。

2024最新激活全家桶教程,稳定运行到2099年,请移步至置顶文章:https://sigusoft.com/99576.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。 文章由激活谷谷主-小谷整理,转载请注明出处:https://sigusoft.com/90038.html

(0)
上一篇 2024年 6月 18日 上午9:47
下一篇 2024年 6月 18日 上午9:56

相关推荐

关注微信