数据结构C代码栈及括号匹配 以下是一个使用栈来实现括号匹配的C语言代码示例: “`c #include <stdio.h> #include <stdbool.h> #define STACK_MAX_SIZE 100 typedef struct CharStack { int top; char data[STACK_MAX_SIZE]; } CharStack; void initStack(CharStack *stack) { stack->top = -1; } bool isEmpty(CharStack *stack) { return stack->top == -1; } bool isFull(CharStack *stack) { return stack->top == STACK_MAX_SIZE – 1; } void push(CharStack *stack, char c) { if (isFull(stack)) { printf(“Stack is full. Cannot push element. ”); return; } stack->data[++stack->top] = c; } char pop(CharStack *stack) { if (isEmpty(stack)) { printf(“Stack is empty. Cannot pop element. ”); return ‘0’; } return stack->data[stack->top–]; } bool isMatchingPair(char opening, char closing) { if (opening == ‘(‘ && closing == ‘)’) return true; else if (opening == ‘{‘ && closing == ‘}’) return true; else if (opening == ‘[‘ && closing == ‘]’) return true; else return false; } bool isBalanced(char expression[]) { CharStack stack; initStack(&stack); for (int i = 0; expression[i] != ‘0’; i++) { if (expression[i] == ‘(‘ || expression[i] == ‘{‘ || expression[i] == ‘[‘) { push(&stack, expression[i]); } else if (expression[i] == ‘)’ || expression[i] == ‘}’ || expression[i] == ‘]’) { if (isEmpty(&stack) || !isMatchingPair(pop(&stack), expression[i])) { return false; } } } return isEmpty(&stack); } int main() { char expression[100]; printf(“Enter an expression: “); fgets(expression, sizeof(expression), stdin); if (isBalanced(expression)) { printf(“The expression is balanced. ”); } else { printf(“The expression is not balanced. ”); } return 0; } “`
2024最新激活全家桶教程,稳定运行到2099年,请移步至置顶文章:https://sigusoft.com/99576.html
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。 文章由激活谷谷主-小谷整理,转载请注明出处:https://sigusoft.com/43402.html