栈的括号匹配的C语言代码
时间: 2024-04-11 07:33:31 浏览: 122
当然,下面是一个简单的栈的括号匹配的 C 语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// 定义栈结构
typedef struct {
char data[MAX_SIZE];
int top;
} Stack;
// 初始化栈
void init(Stack *stack) {
stack->top = -1;
}
// 判断栈是否为空
int isEmpty(Stack *stack) {
return stack->top == -1;
}
// 判断栈是否已满
int isFull(Stack *stack) {
return stack->top == MAX_SIZE - 1;
}
// 入栈操作
void push(Stack *stack, char item) {
if (isFull(stack)) {
printf("Stack is full.\n");
return;
}
stack->data[++stack->top] = item;
}
// 出栈操作
char pop(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return '\0';
}
return stack->data[stack->top--];
}
// 括号匹配函数
int isBalanced(char expression[]) {
Stack stack;
init(&stack);
int i = 0;
char current_char;
while (expression[i] != '\0') {
current_char = expression[i];
if (current_char == '(' || current_char == '[' || current_char == '{') {
push(&stack, current_char);
} else if (current_char == ')' || current_char == ']' || current_char == '}') {
if (isEmpty(&stack)) {
return 0;
} else if ((current_char == ')' && stack.data[stack.top] == '(') ||
(current_char == ']' && stack.data[stack.top] == '[') ||
(current_char == '}' && stack.data[stack.top] == '{')) {
pop(&stack);
} else {
return 0;
}
}
i++;
}
return isEmpty(&stack);
}
int main() {
char expression[MAX_SIZE];
printf("请输入一个表达式: ");
fgets(expression, sizeof(expression), stdin);
if (isBalanced(expression)) {
printf("括号匹配正确.\n");
} else {
printf("括号匹配错误.\n");
}
return 0;
}
```
这段代码实现了栈的基本操作,并通过 `isBalanced` 函数来判断一个表达式中的括号是否匹配。你可以通过输入一个表达式来测试代码中的括号匹配功能。
阅读全文