使用c语言利用链栈完成括号匹配判断
时间: 2023-08-07 13:05:17 浏览: 65
好的,以下是使用链栈实现括号匹配的C语言代码,希望能帮到您:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// 定义链栈节点结构体
typedef struct Node {
char data;
struct Node *next;
} Node;
// 定义链栈结构体
typedef struct Stack {
Node *top; // 栈顶指针
} Stack;
// 初始化链栈
Stack* initStack() {
Stack *s = (Stack*)malloc(sizeof(Stack));
s->top = NULL;
return s;
}
// 判断链栈是否为空
bool isEmpty(Stack *s) {
return s->top == NULL;
}
// 进栈
void push(Stack *s, char data) {
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = s->top;
s->top = node;
}
// 出栈
char pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
return '\0';
}
Node *node = s->top;
char data = node->data;
s->top = node->next;
free(node);
return data;
}
// 判断括号是否匹配
bool isMatch(char left, char right) {
if (left == '(' && right == ')') {
return true;
} else if (left == '[' && right == ']') {
return true;
} else if (left == '{' && right == '}') {
return true;
} else {
return false;
}
}
// 判断括号序列是否匹配
bool isBracketMatch(char *str) {
Stack *s = initStack();
int i = 0;
while (str[i] != '\0') {
if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
push(s, str[i]);
} else if (str[i] == ')' || str[i] == ']' || str[i] == '}') {
if (isEmpty(s) || !isMatch(pop(s), str[i])) {
return false;
}
}
i++;
}
return isEmpty(s);
}
int main() {
// 测试括号匹配
char str1[] = "(((())))";
char str2[] = "([{}])";
char str3[] = "([]})";
printf("%s\n", isBracketMatch(str1) ? "Match" : "Not match");
printf("%s\n", isBracketMatch(str2) ? "Match" : "Not match");
printf("%s\n", isBracketMatch(str3) ? "Match" : "Not match");
return 0;
}
```
以上是一个简单的括号匹配示例,可以在其中添加更多的操作,如获取栈顶元素等,以满足您的需求。