栈的应用-括号的匹配检验

问题描述

假设表达式中允许包含两种括号:圆括号和方括号,其嵌套的顺序随意,即([]())或[([][])]等为正确的格式,[(]或[())]等为非法格式,试写一个算法检验括号的格式是否正确。

解题思路

        使用栈这种数据结构,当遇到左半边的符号时,进栈,如遇到右半边的符号时,出栈操作,如果符号不是同一队符号,则重新入栈,程序结束后,根据栈是否为空栈判断括号的格式是否正确,如果是正确,则栈为空栈,否则相反。

        程序是根据严蔚敏老师的数据结构一书写就的,最后判断括号是否全匹配的操作我有点迷。

程序实现

#include <stdio.h>
#include <stdlib.h>

/**
 * 栈的简单操作:判断括号是否成对
 */
#define STACK_INIT_SIZE 100
typedef struct Stack {
	char *base;
	char *top;
	int stackSize;
} SqStack;
void initStack(SqStack *stack);
int pushStack(SqStack *stack, char element);
int popStack(SqStack *stack, char *element);
int main(int argc, char *argv[]) {
	SqStack stack;
	initStack(&stack);
	printf("请输入要匹配的括号:\n");
	char element, result;
	scanf("%c", &element);
	while (element != '#') {
		if ((int)element == 91 || (int)element == 40) {
			pushStack(&stack, element);
		} else {
			popStack(&stack, &result);
			if ((element == ']' && result != '[') || (element == ')' && result != '(')) {
				pushStack(&stack, result);
			}
		}
		getchar();
		scanf("%c", &element);
	}
	if (*stack.top == *stack.base) {
		printf("括号全匹配!");
	} else {
		printf("括号匹配失败!");
	}
	return 0;
}

/**
 * 初始化栈
 */
void initStack(SqStack *stack) {
	stack->base = (char *)malloc(STACK_INIT_SIZE * sizeof(char));
	if (!stack->base) {
		exit(-1);
	}
	stack->stackSize = 100;
	stack->top = stack->base;
}

/**
 * 入栈操作
 */
int pushStack(SqStack *stack, char element) {
	// 栈已满
	if (stack->top - stack->base >= stack->stackSize) {
		return -1;
	}
	*stack->top++ = element;
	return 1;
}

/**
 * 出栈操作
 */
int popStack(SqStack *stack, char *element) {
	// 栈已空
	if (stack->top == stack->base) {
		return -1;
	}
	*element = *--stack->top;
	return 1;
}


转载于:https://my.oschina.net/niithub/blog/3032093

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值