【数据结构栈应用系列】括号匹配

括号匹配算法在各种编程的IDE工具中都会用到,用来检测关于括号匹配的语法错误,括号匹配实际上不复杂,主要就是利用栈这个数据结构,扫描输入的字符串,若遇到左括号则直接入栈,若遇到右括号则弹出栈顶括号,看是否与当前括号类型相同(如同为小括号(),或同为[],注意括号应该是在英文输入法的情况下输入的),若相同则二者匹配,否则不匹配,另外,如果扫描完成,而栈中仍存在未匹配的括号,则说明不匹配,当且仅当扫描序列与栈中元素同时为空时才表示完全匹配。本博客将详细讲解括号匹配算法,为了将焦点聚焦在算法本身上,仅仅只对小括号进行检测是否匹配。

注:关于栈的另外一个典型应用就是表达式求值算法,类似于计算器效果,具体可以参看我的博客:算术表达式


# include<stdio.h>
# include<string.h>
# include<stdlib.h>
typedef struct node
{
	char a;
	struct node *pnext;
}node,*linklist;
void inistack(linklist s)
{
	(s)->pnext=NULL;
}
void push(linklist top,char c)
{
	linklist ptemp=(linklist)malloc(sizeof(node));
	(ptemp)->a=c;
	ptemp->pnext=(top)->pnext;
	(top)->pnext=ptemp;
	
}
void pop(linklist top,char* c)
{
	linklist ptemp;
	ptemp=(top)->pnext;
	*c=(ptemp)->a;
	if(ptemp==NULL)
		printf("栈空!");
	(top)->pnext=ptemp->pnext;
	free(ptemp);
}
void get(linklist top,char *x)
{
	*x=top->pnext->a;
}
int isempty(linklist s)
{
	if(s->pnext==NULL)
		return 1;
	else return 0;
}
int match(char x,char y)
{
	if((x=='(')&&(y==')'))
		return 1;
	else return 0;
}
void Match(char x[])
{
	node s;
	int i;
	char ch;
	inistack(&s);
	for(i=0;x[i]!='\0';i++)
	{
		if(x[i]=='(')
		{
			push(&s,x[i]);
		}
		else
			if(isempty(&s))
			{
				printf("右括号多余!\n");
				return;
			}
			else
			{
				get(&s,&ch);
				if(match(ch,x[i]))
				{
					pop(&s,&ch);
				}
				
				else
				{
					printf("对应的括号不匹配!\n");
					return;
				}
			}
	}
	if(isempty(&s))
		printf("括号匹配!\n");
	else
		printf("左括号多余!\n");
}
void main()
{
	int i;
	char x[20];
	printf("请输入只含小括号的字符串\n");
	scanf("%s",x);
	Match(x);	
}
程序运行结果如下:




posted on 2016-03-26 16:59  海南一哥  阅读(519)  评论(0编辑  收藏  举报

导航