c语言通过栈判断括号匹配是否配对

概述

前面实现了栈的基本数据结构,这里来做一个联系,用栈来解决一道比较常见的算法题,就是括号配对是否满足规则。

实现

描述

给定一组括号,判断是否满足配对。

代码

c 复制代码
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#define bool char 
#define true 1
#define MAX_LEN 10
#define false 0
typedef  char ElementType;
typedef struct Stack {
	int top;
	ElementType stackList[MAX_LEN];
} Stack;
bool fn(char arr[], int len, Stack* S);
bool push(Stack* S, ElementType data);
bool pop(Stack* S, ElementType* x);
bool intStack(Stack* S);
int main() {
	Stack S;
	intStack(&S);
	char brackList[] = {'(', '{','(',')','}','{','}','}' };
	printf("%d", fn(brackList, sizeof(brackList) / sizeof(brackList[0]), &S));
}
bool fn(char arr[], int len, Stack* S) {
	for (int i = 0; i < len; i++) {
		if (arr[i] == '{' || arr[i] == '(') {
			push(S,arr[i]);
			printf("%c", arr[i]);
		}
		else {
			if (S->top == 0) {
				return false;
			}
			ElementType topData;
			pop(S, &topData);
			if (topData == '(' && arr[i] != ')') {
				return false;
			}
			else if (topData == '{' && arr[i] != '}') {
				return false;
			}
		}
	}
	if (S->top == 0) {
		return true;
	}
	return false;
}
//初始化
bool intStack(Stack* S) {
	for (int i = 0; i < MAX_LEN; i++) {
		S->stackList[i] = 0;
	}
	S->top = 0;
	return true;
}
//入栈
bool push(Stack* S,ElementType data) {
	S->top++;
	S->stackList[S->top] = data;
	return true;
}
//出栈
bool pop(Stack* S, ElementType *x) {
	*x = S->stackList[S->top];
	S->stackList[S->top] = 0;
	S->top--;
	return true;
}
相关推荐
想用offer打牌4 小时前
MCP (Model Context Protocol) 技术理解 - 第二篇
后端·aigc·mcp
2601_949146536 小时前
C语言语音通知接口接入教程:如何使用C语言直接调用语音预警API
c语言·开发语言
KYGALYX6 小时前
服务异步通信
开发语言·后端·微服务·ruby
掘了6 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
爬山算法6 小时前
Hibernate(90)如何在故障注入测试中使用Hibernate?
java·后端·hibernate
Moment7 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
Cobyte8 小时前
AI全栈实战:使用 Python+LangChain+Vue3 构建一个 LLM 聊天应用
前端·后端·aigc
知南x8 小时前
【Ascend C系列课程(高级)】(1) 算子调试+调优
c语言·开发语言
程序员侠客行8 小时前
Mybatis连接池实现及池化模式
java·后端·架构·mybatis
Honmaple8 小时前
QMD (Quarto Markdown) 搭建与使用指南
后端