用栈实现成对括号检查 (Check bracket base on Stack)

问题描述:从左至右读取表达式,读到运算对象和运算符,不做任何动作,直接往下继续读,读到括号,要对括号的使用是否正确进行检查。
如:   {[ ]( [ ][ ])}   为合法

代码如下:
#include
#include
#include
#define MAXSIZE 20
typedef struct SeqStack
{
	char data[MAXSIZE];
	int top;
}SeqStack;

int Bracket_Check(char *a)
{
	int i;
	SeqStack s;
	s.top = -1;
	for (i = 0; a[i] != '\0'; i++)
	{
		if (a[i] == '(' || a[i] == '[' || a[i] == '{')
			s.data[++s.top] = a[i];
		if (a[i] == ')' || a[i] == ']' || a[i] == '}')
		{
			if ((a[i] == ')' && s.data[s.top] == '(') || (a[i] == ']' && s.data[s.top] == '[') || (a[i] == '}' && s.data[s.top] == '{'))
				s.top--;
			else
				return 0;		
		}
	}
	if (s.top == -1)
		return 1;
	else
		return 0;
}

int main()
{
	char input[MAXSIZE];
	int check;
	gets_s(input, MAXSIZE);
	check = Bracket_Check(input);
	if (check)
		printf("Yes\n");
	else
		printf("No\n");
	system("pause");
}
编译环境: Visual Studio

你可能感兴趣的:(Data,Strutures,and,Algorithm,Stack,C)