使用c语言实现括号匹配
时间: 2023-10-03 20:06:52 浏览: 102
下面是使用C语言实现括号匹配的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// 定义栈结构体
typedef struct {
char data[MAX_SIZE]; // 数组存储栈元素
int top; // 栈顶指针
} Stack;
// 初始化栈
void initStack(Stack *s) {
s->top = -1;
}
// 判断栈是否为空
int isEmpty(Stack *s) {
return s->top == -1;
}
// 判断栈是否已满
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
// 入栈
void push(Stack *s, char c) {
if (isFull(s)) {
printf("Stack is full!\n");
exit(1);
}
s->data[++s->top] = c;
}
// 出栈
char pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty!\n");
exit(1);
}
return s->data[s->top--];
}
// 括号匹配函数
int match(char *exp) {
Stack s;
initStack(&s);
char c;
while (*exp) {
switch (*exp) {
case '(':
case '[':
case '{':
push(&s, *exp);
break;
case ')':
if (isEmpty(&s) || pop(&s) != '(')
return 0;
break;
case ']':
if (isEmpty(&s) || pop(&s) != '[')
return 0;
break;
case '}':
if (isEmpty(&s) || pop(&s) != '{')
return 0;
break;
default:
break;
}
exp++;
}
return isEmpty(&s); // 如果栈为空则表示括号匹配成功
}
int main() {
char exp[MAX_SIZE];
printf("Enter an expression: ");
scanf("%s", exp);
if (match(exp))
printf("Matching succeeded!\n");
else
printf("Matching failed!\n");
return 0;
}
```
代码中使用了栈的数据结构来实现括号匹配,遍历输入的表达式,当遇到左括号时,将其入栈,当遇到右括号时,从栈中弹出一个元素并与之匹配,如果匹配成功则继续遍历,否则返回匹配失败。最后判断栈是否为空,如果栈为空则表示括号匹配成功,否则匹配失败。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)