用c写出栈的入栈 出栈 检查括号是否匹配的函数操作
时间: 2024-10-20 15:05:48 浏览: 36
在C语言中,我们可以使用数组或链表来实现一个简单的栈结构,用于入栈、出栈和检查括号是否匹配。这里我们假设使用字符型数据(如字符'a'到'e'代表左括号'(',')','{', '}'等),并仅处理一对匹配的括号。
```c
#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 100
// 定义栈结构
typedef struct {
char stack[MAX_SIZE];
int top;
} Stack;
// 初始化栈
void init(Stack *s) {
s->top = -1;
}
// 判断是否为空
bool isEmpty(Stack *s) {
return s->top == -1;
}
// 入栈
void push(Stack *s, char c) {
if (s->top < MAX_SIZE - 1) {
s->stack[++s->top] = c;
} else {
printf("Stack overflow!\n");
}
}
// 出栈
char pop(Stack *s) {
if (!isEmpty(s)) {
return s->stack[s->top--];
} else {
printf("Stack underflow!\n");
return '\0'; // 返回空字符表示错误
}
}
// 检查括号是否匹配
bool isParenthesesMatch(Stack *s) {
Stack tempStack;
init(&tempStack);
while (!isEmpty(s)) {
char c = pop(s);
if (c == '(' || c == '{' || c == '[') {
push(&tempStack, c);
} else {
if (tempStack.top > 0 && tempStack.stack[tempStack.top - 1] == '(' && c == ')') {
tempStack.top--;
} else if (tempStack.top > 0 && tempStack.stack[tempStack.top - 1] == '{' && c == '}') {
tempStack.top--;
} else if (tempStack.top > 0 && tempStack.stack[tempStack.top - 1] == '[' && c == ']') {
tempStack.top--;
} else {
return false; // 匹配失败
}
}
}
return isEmpty(&tempStack); // 如果临时栈也为空,则原始栈的所有括号都已匹配
}
int main() {
Stack s;
init(&s);
// 示例操作
push(&s, '(');
push(&s, ')');
push(&s, '{');
push(&s, '}');
if (isParenthesesMatch(&s)) {
printf("Parentheses match.\n");
} else {
printf("Parentheses do not match.\n");
}
return 0;
}
```
阅读全文
相关推荐


















