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;
}
相关推荐
蝎子莱莱爱打怪2 分钟前
那不是我的黑历史,那是我的来时路啊!😭😭
后端·程序员
用户298698530143 分钟前
Java 实现 Word 文档文本与图片提取的方法
java·后端
蝎子莱莱爱打怪11 分钟前
XZLL-IM干货系列 04|Netty 长连接实战:Pipeline 怎么排、心跳怎么跳、连接怎么管
后端·微服务·面试
Csvn17 分钟前
Rsync 文件同步与增量备份 — 运维的数据守门员
后端
苏三说技术19 分钟前
推荐一个牛逼的智能代码审查系统
后端
倾颜26 分钟前
从 GitHub Actions 到本地兜底发布:AI Mind 容器化上线的一次真实收口
后端
像我这样帅的人丶你还34 分钟前
Java 后端详解(二):注解、参数绑定、评论与用户认证
后端
用户7623524259135 分钟前
深入理解AQS之独占锁ReentrantLock
后端
用户7623524259141 分钟前
理解 CAS & Atomic 原子操作类
后端
SimonKing1 小时前
铁子,IntelliJ IDEA 2026.1.3来了,升不升?
java·后端·程序员