1. 程式人生 > >更多內容請訪問我的個人官方網站www.huqi.tech

更多內容請訪問我的個人官方網站www.huqi.tech

括號匹配演算法在各種程式設計的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);	
}
程式執行結果如下: