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;
}
相关推荐
Lizhihao_14 分钟前
Spring MVC 接口的访问方法如何设置
java·后端·spring·mvc
瓦力wow3 小时前
c语言 写一个五子棋
c语言·c++·算法
hjjdebug3 小时前
c/c++数据类型转换.
c语言·c++·数据类型变换
花火QWQ4 小时前
图论模板(部分)
c语言·数据结构·c++·算法·图论
Pacify_The_North4 小时前
【进程控制二】进程替换和bash解释器
linux·c语言·开发语言·算法·ubuntu·centos·bash
wuqingshun3141594 小时前
经典算法 (A/B) mod C
c语言·开发语言·c++·算法·蓝桥杯
半青年4 小时前
Qt图表库推荐指南与分析
c语言·开发语言·javascript·c++·qt·信息可视化
Code哈哈笑4 小时前
【图书管理系统】用户注册系统实现详解
数据库·spring boot·后端·mybatis
用手手打人4 小时前
SpringBoot(一)--- Maven基础
spring boot·后端·maven
ShineSpark5 小时前
C++面试2——C与C++的关系
c语言·c++·面试