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

2023年 9月 21日 56.1k 0

概述

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

实现

描述

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

代码

#include
#include
#include
#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 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 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;
}

相关文章

如何删除WordPress中的所有评论
检查WordPress服务器磁盘使用情况的7种简便方法(查找大文件和数据)
如何更改WordPress常量FS_METHOD
如何为区块编辑器、Elementor等构建WordPress文章模板
如何彻底地删除WordPress主题及相关内容
如何使用WordPress搭建一个内网

发布评论