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;
}
相关推荐
小王不爱笑1326 小时前
Spring AOP(AOP+JDBC 模板 + 转账案例)
java·后端·spring
Python私教6 小时前
Rust基本语法
后端
Python私教6 小时前
Rust环境搭建
后端
jakeswang6 小时前
ServletLess架构简介
java·后端·servletless
夕颜1117 小时前
如何让 AI 按照你的预期输出
后端
q***56387 小时前
Spring Boot--@PathVariable、@RequestParam、@RequestBody
java·spring boot·后端
com_4sapi7 小时前
2025 权威认证头部矩阵系统全景对比发布 双榜单交叉验证
大数据·c语言·人工智能·算法·矩阵·机器人
q***57508 小时前
Spring Boot(七):Swagger 接口文档
java·spring boot·后端
芯联智造9 小时前
【stm32协议外设篇】- PAJ7620手势识别传感器
c语言·stm32·单片机·嵌入式硬件
猪猪拆迁队9 小时前
前端图形引擎架构设计:双引擎架构设计
前端·后端·架构