c语言数据结构括号匹配的检验代码case
时间: 2023-05-26 12:05:56 浏览: 108
以下是一个简单的基于栈的括号匹配检验的c语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct stack {
char *data;
int top;
int size;
} Stack;
void init(Stack *s, int size) // 初始化栈
{
s->size = size;
s->top = -1;
s->data = (char *)malloc(sizeof(char)*size);
if (s->data == NULL) {
perror("malloc");
exit(1);
}
}
bool is_empty(Stack *s)
{
return s->top == -1;
}
bool is_full(Stack *s)
{
return s->top == s->size-1;
}
char top(Stack *s)
{
if (is_empty(s)) {
fprintf(stderr, "Stack is empty.\n");
exit(1);
}
return s->data[s->top];
}
void push(Stack *s, char ch)
{
if (is_full(s)) {
fprintf(stderr, "Stack is full.\n");
exit(1);
}
s->top++;
s->data[s->top] = ch;
}
void pop(Stack *s)
{
if (is_empty(s)) {
fprintf(stderr, "Stack is empty.\n");
exit(1);
}
s->top--;
}
void destroy(Stack *s)
{
free(s->data);
s->data = NULL;
s->size = 0;
s->top = -1;
}
bool is_match(char left, char right)
{
if (left == '(' && right == ')') return true;
if (left == '{' && right == '}') return true;
if (left == '[' && right == ']') return true;
return false;
}
bool check_match(const char *str)
{
Stack s;
init(&s, 100);
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == '(' || str[i] == '{' || str[i] == '[') {
push(&s, str[i]);
}
else if (str[i] == ')' || str[i] == '}' || str[i] == ']') {
if (is_empty(&s)) {
destroy(&s);
return false;
}
char left = top(&s);
if (is_match(left, str[i])) {
pop(&s);
}
else {
destroy(&s);
return false;
}
}
}
bool ret = is_empty(&s);
destroy(&s);
return ret;
}
int main(int argc, char *argv[])
{
if (argc != 2) {
fprintf(stderr, "Usage: %s \"string to check\"\n", argv[0]);
return 1;
}
if (check_match(argv[1])) {
printf("Match successful.\n");
}
else {
printf("Match failed.\n");
}
return 0;
}
```
该代码中,我们定义了一个 Stack 结构体来存储括号序列。接着实现了初始化 init,判断是否为空、判断是否已满、获取栈顶元素 top、入栈 push、出栈 pop、清空 destroy 函数。其中,is_match 函数用来匹配左右括号是否匹配。最后,check_match 函数是用来检查输入字符串中的括号序列是否匹配,如果匹配则返回 true,否则返回 false。在 main 函数中,我们首先判断命令行参数是否正确,如果正确则调用 check_match 函数检查输入字符串中的括号序列是否匹配。
阅读全文