首页 > 其他 > 详细

栈的应用之括号匹配

时间:2015-05-09 17:35:27      阅读:111      评论:0      收藏:0      [点我收藏+]

思路:

在算法中设置一个栈,每读入一个空号

一:若是右括号: ‘}‘  ‘ )‘   ‘]‘(两种情况):

1:使置于栈顶的最急迫的期待得以消解,需将栈顶元素出栈;

2:不合法的情况,即与栈顶的最急迫的期待不匹配,需将其(括号)压栈;

二:若是左括号:‘(‘  ‘{‘  ‘[‘

作为一个新的更急迫的期待压栈;

顺序栈的代码不再赘述点击打开链接

							//括号匹配
#include"stack.h"
int main()
{
	Stack st;
	InitStack(&st);
	int flag = 1;
	
	while(flag)
	{
		/*要测试的一串括号*/
		char str[100] ;
		cout<<"请输入一串括号:"<<endl;
		scanf("%s",str);

		char *p = str;//指向字符串数组
		char e;

		while(*p != '\0')
		{

			if(*p == '[' || *p == '{' || *p == '(')
			{	
				Push(&st,*p);
				p++;
			}
			else
			{
				if(*p == ']')
				{
					if(st.base[st.top - 1] == '[')
						Pop(&st,&e);
					else
						Push(&st,*p);
				}
				if(*p == ')')
				{
					if(st.base[st.top - 1] == '(')
						Pop(&st,&e);
					else
						Push(&st,*p);
				}
				if(*p == '}')
				{
					if(st.base[st.top - 1] == '{')
						Pop(&st,&e);
					else
						Push(&st,*p);
				}
				p++;
			}	
		}
		if(st.top == 0)
			cout<<"括号匹配"<<endl;
		else
			cout<<"括号不匹配"<<endl;

		cout<<"continue:1  break:0"<<endl;
		cin>>flag;
	
	}
	destory(&st);
	return 0;
}
技术分享

改进后代码:

							//括号匹配
#include"stack.h"
int main()
{
	Stack st;
	InitStack(&st);
	int flag = 1;
	
	while(flag)
	{

		char str[100];
		cout<<"请输入一串括号:"<<endl;
		scanf("%s",str); //用cin为何是错误的????

		char *p = str;
		char e;

		while(*p != '\0')
		{

			if(*p == '[' || *p == '{' || *p == '(')
			{	
				Push(&st,*p);
				p++;
			}
			else
			{
				if( (*p == ']' && st.base[st.top - 1] == '[')
					||(*p == '}' && st.base[st.top - 1] == '{')
					  ||(*p == ')' && st.base[st.top - 1] == '(')
					  )
					  Pop(&st,&e);
				else
					Push(&st,*p);
					p++;
			}	
		}
		if(st.top == 0)
				cout<<"括号匹配"<<endl;
		else
				cout<<"括号不匹配"<<endl;
		cout<<"continue:1  break:0"<<endl;
		cin>>flag;
	}
	destory(&st);
	return 0;
}


栈的应用之括号匹配

原文:http://blog.csdn.net/zongyinhu/article/details/45602255

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!