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;
}
相关推荐
RANCE_atttackkk27 分钟前
Springboot+langchain4j的RAG检索增强生成
java·开发语言·spring boot·后端·spring·ai·ai编程
梵刹古音30 分钟前
【C语言】 格式控制符与输入输出函数
c语言·开发语言·嵌入式
VekiSon1 小时前
Linux内核驱动——基础概念与开发环境搭建
linux·运维·服务器·c语言·arm开发
无限进步_1 小时前
面试题 02.02. 返回倒数第 k 个节点 - 题解与详细分析
c语言·开发语言·数据结构·git·链表·github·visual studio
Hello World . .1 小时前
数据结构:栈和队列
c语言·开发语言·数据结构·vim
好好研究2 小时前
Spring Boot - Thymeleaf模板引擎
java·spring boot·后端·thymeleaf
爬山算法2 小时前
Hibernate(76)如何在混合持久化环境中使用Hibernate?
java·后端·hibernate
她说..2 小时前
策略模式+工厂模式实现单接口适配多审核节点
java·spring boot·后端·spring·简单工厂模式·策略模式
csdn_aspnet2 小时前
ASP.NET 8 - Cookie 身份验证
后端·asp.net·cookie·.net8
笔画人生2 小时前
Cursor + 蓝耘API:用自然语言完成全栈项目开发
前端·后端