用C语言写一个栈的括号匹配程序
时间: 2023-11-23 15:07:55 浏览: 76
以下是一个简单的栈的括号匹配程序,使用C语言实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define SIZE 100
char stack[SIZE];
int top = -1;
void push(char c) {
if (top == SIZE - 1) {
printf("Stack Overflow!\n");
exit(1);
}
stack[++top] = c;
}
char pop() {
if (top == -1) {
printf("Stack Underflow!\n");
exit(1);
}
return stack[top--];
}
int is_matching_pair(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 is_balanced(char exp[]) {
int i;
char popped_char;
for (i = 0; exp[i] != '\0'; i++) {
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[') {
push(exp[i]);
}
else if (exp[i] == ')' || exp[i] == '}' || exp[i] == ']') {
if (top == -1) return 0;
popped_char = pop();
if (!is_matching_pair(popped_char, exp[i])) return 0;
}
}
if (top == -1) return 1;
else return 0;
}
int main() {
char exp[SIZE];
printf("Enter an expression: ");
fgets(exp, SIZE, stdin);
if (is_balanced(exp)) printf("Expression is balanced.\n");
else printf("Expression is not balanced.\n");
return 0;
}
```
程序首先定义了一个栈和一个栈顶指针。栈的大小为100。`push()`和`pop()`分别用于在栈中压入和弹出字符。`is_matching_pair()`用于检查字符是否匹配。`is_balanced()`函数用于检查括号是否匹配。程序会从用户输入中读取一个表达式,然后调用`is_balanced()`函数检查它是否括号匹配。如果匹配,程序将输出“Expression is balanced.”,否则将输出“Expression is not balanced.”。
阅读全文