判断表达式中括号是否匹配(栈的典型应用)(某公司校园招聘笔试试题)

#include<iostream>
using namespace std;

typedef char Type;

typedef struct node
{
	Type data;
	struct node *next;
}Node, *Stack;

void initiateStack(Stack &s)
{
	s = new Node;
	s->next = NULL;
}

bool isEmptyStack(Stack &s)
{
	if(NULL == s)
	{
		cout << "栈不存在." << endl;
		exit(0);
	}

	if(NULL == s->next)
		return true;

	return false;
}

void push(Stack &s, Type element)
{
	Node *p = new Node;
	p->data = element;
	p->next = s->next;
	s->next = p;
}

Type pop(Stack &s)
{
	if(isEmptyStack(s))
	{
		exit(1);
	}

	Node *p = s->next;
	s->next = p->next;

	Type element = p->data;
	delete p;

	return element;
}

int getLength(Stack &s)
{
	Node *p = s;
	int length = 0;
	while(NULL != p->next)
	{
		p = p->next;
		length++;
	}

	return length;
}

Type getTop(Stack &s)
{
	if(isEmptyStack(s))
		exit(1);

	return s->next->data;
}

void clearStack(Stack &s)
{
	while(!isEmptyStack(s))
		pop(s);
}

void destoryStack(Stack &s)
{
	while(!isEmptyStack(s))
		pop(s);

	delete s;
	s = NULL;
}

//左右匹配
bool match(char c1, char c2)
{
	if( '(' == c1 && ')' == c2)
		return true;
	if( '[' == c1 && ']' == c2)
		return true;
	if( '{' == c1 && '}' == c2)
		return true;
	
	return false;
}

//左括号
bool isLeftBracket(char c)
{
	if('(' == c || '[' == c || '{' == c)
		return true;

	return false;
}

//右括号
bool isRightBracket(char c)
{
	if(')' == c || ']' == c || '}' == c)
		return true;

	return false;
}

//判断表达式中括号是否匹配
bool isExpressionLegal(char str[])
{
	Stack s;
	initiateStack(s);
	int i;
	for(i = 0; str[i]; i++)
	{
		if(isLeftBracket(str[i]))//遇到左括号,进栈
			push(s, str[i]);

		if(isRightBracket(str[i]))//遇到右括号,分情况讨论
		{
			if(isEmptyStack(s))
			{				
				destoryStack(s);
				return false;
			}

			if(!match(pop(s), str[i]))
			{
				destoryStack(s);
				return false;
			}
		}
	}

	if(!isEmptyStack(s))//栈中还有左括号
	{
		destoryStack(s);
		return false;
	}
	
	//如果不出现上面的情况,则必定是匹配的
	destoryStack(s);
	return true;

}

void print(bool b)
{
	if(b)
		cout << "yes" << endl;
	else
		cout << "no" << endl; 
}

int main()
{
	char str1[] = "(3 + 2)";
	print(isExpressionLegal(str1));

	char str2[] = "(3 + 2))";
	print(isExpressionLegal(str2));

	char str3[] = "((3 + 2)";
	print(isExpressionLegal(str3));

	char str4[] = "(3 + 2]";
	print(isExpressionLegal(str4));

	char str5[] = "{3 + 2]";
	print(isExpressionLegal(str5));

	char str6[] = "[3 + 2]";
	print(isExpressionLegal(str6));

	char str7[] = "[(3 + 2])";
	print(isExpressionLegal(str7));

	char str8[] = "5 * [(1 * {3 + 2}) * 4]";
	print(isExpressionLegal(str8));

	return 0;
}

 

 

你可能感兴趣的:(判断表达式中括号是否匹配(栈的典型应用)(某公司校园招聘笔试试题))