C语言用栈实现括号匹配代码
时间: 2023-10-26 13:09:04 浏览: 113
用栈实现括号匹配算法
好的,以下是用C语言实现栈的括号匹配代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
//定义栈结构体
typedef struct {
int top;
int capacity;
char *array;
} Stack;
//创建栈
Stack *createStack(int capacity) {
Stack *stack = malloc(sizeof(Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = malloc(stack->capacity * sizeof(char));
return stack;
}
//判断栈是否为空
bool isEmpty(Stack *stack) {
return stack->top == -1;
}
//判断栈是否已满
bool isFull(Stack *stack) {
return stack->top == stack->capacity - 1;
}
//入栈
void push(Stack *stack, char item) {
if (isFull(stack)) {
printf("栈已满\n");
return;
}
stack->top++;
stack->array[stack->top] = item;
}
//出栈
char pop(Stack *stack) {
if (isEmpty(stack)){
printf("栈已空\n");
return '\0';
}
char item = stack->array[stack->top];
stack->top--;
return item;
}
//获取栈顶元素
char peek(Stack *stack) {
return stack->array[stack->top];
}
//匹配括号
bool isPair(char opening, char closing) {
if (opening == '(' && closing == ')') {
return true;
} else if (opening == '[' && closing == ']') {
return true;
} else if (opening == '{' && closing == '}') {
return true;
}
return false;
}
//判断括号是否匹配
bool isBalanced(char *exp) {
Stack *stack = createStack(100);
for (int i = 0; exp[i] != '\0'; i++) {
if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{') {
push(stack, exp[i]);
} else if (exp[i] == ')' || exp[i] == ']' || exp[i] == '}') {
if (isEmpty(stack) || !isPair(peek(stack), exp[i])) {
return false;
} else {
pop(stack);
}
}
}
return isEmpty(stack);
}
int main() {
char exp[100]; //用于存放表达式的字符串
printf("请输入表达式:\n");
scanf("%s", exp);
if (isBalanced(exp)) {
printf("括号匹配成功!\n");
} else {
printf("括号匹配失败!\n");
}
return 0;
}
```
希望能对你有所帮助,如果还有其它问题,请继续提出。现在,也让我来讲一个笑话吧:什么样的猪最喜欢读书?——“书呆猪”!
阅读全文