栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

数据结构我好爱:栈的应用--括号匹配

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构我好爱:栈的应用--括号匹配

我们可以通过栈来匹配括号是否齐全:把左括号压入栈,当遇见右括号且与栈顶括号匹配的时候,我们将栈顶的左括号弹出,继续检验。

简直就是用栈的完美特性“先进后出”

常规操作:压栈与入栈就不说了!

主要函数:括号匹配函数:

        1.开始逐个遍历字符串

        2.将左括号读入

        3.如果有拥有右括号且与栈顶括号匹配,弹出栈顶,否则return 0;

        4.防止最后一个元素为左括号压入了栈,检查栈顶是否为提前设置的#,否则return 0

        5.最终return 1,括号匹配成功

int baketJudge(char* str) {
	stackPtr head = InitStack();
	push(head, '#');
	char topc;
	for (int i = 0; i < strlen(str); i++) {
		char tempc = str[i];

		switch (tempc) {
		case '(':
		case '[':
		case '{':
			push(head, tempc);
			break;
		case ')':
			topc = pop(head);
			if (topc != '(') return 0;
			break;
		case ']':
			topc = pop(head);
			if (topc != '[') return 0;
			break;
		case '}':
			topc = pop(head);
			if (topc != '{') return 0;
			break;
		default:
			break;
		}
	}
	topc = pop(head);
	if (topc != '#') {
		return 0;
	}
	return 1;
}

 

完整代码:

#include
#include
#include

typedef struct {
	char data[20];
	int top;
}*stackPtr,stack;

void Print(stackPtr head) {
	if (head->top == -1) return;
	for (int i = head->top; i >= 0; i--) {
		printf("%c ", head->data[i]);
	}
}


stackPtr InitStack() {
	stackPtr head = (stackPtr)malloc(sizeof(stack));
	head->top = -1;
	return head;
}

void push(stackPtr head, char c) {
	if (head->top >= 18) {
		printf("no space");
		return;
	}
	head->top++;
	head->data[head->top] = c;
}

char pop(stackPtr head) {
	char tempchar = head->data[head->top];
	head->top--;
	return tempchar;
}

int baketJudge(char* str) {
	stackPtr head = InitStack();
	push(head, '#');
	char topc;
	for (int i = 0; i < strlen(str); i++) {
		char tempc = str[i];

		switch (tempc) {
		case '(':
		case '[':
		case '{':
			push(head, tempc);
			break;
		case ')':
			topc = pop(head);
			if (topc != '(') return 0;
			break;
		case ']':
			topc = pop(head);
			if (topc != '[') return 0;
			break;
		case '}':
			topc = pop(head);
			if (topc != '{') return 0;
			break;
		default:
			break;
		}
	}
	topc = pop(head);
	if (topc != '#') {
		return 1;
	}
	return 1;
}

void Test() {
	char* tempExpression = "[2 + (1 - 3)] * 4";
	printf("%s n", tempExpression);
	if (baketJudge(tempExpression)) printf("truen");
	else printf("falsen");

	char* tempExpression1 = "[2 + (1 - 3)]) * 4";
	printf("%s n", tempExpression1);
	if (baketJudge(tempExpression1)) printf("truen");
	else printf("falsen");
}

int main() {
	Test();
	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/876825.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号