數據結構與算法(10)--棧的應用-括號匹配

//括號匹配

/*算法思想: 
**若是左括號,入棧,若是右括號,則出棧一個左括號判斷是否與之匹配;
**檢驗棧是否爲空,只有棧空,整個字符串纔是括號匹配的。 
*/ 
#include<cstdio>
#include<cstring>
#include<cstdlib>
#define ElemType char
using namespace std;


typedef struct SNode{
	ElemType data;
	struct SNode *next; 
}SNode,*SLink;

typedef struct {
	SLink top;
	int count;
}Stack;

//初始化棧
void InitStack(Stack &s);
//入棧操作
bool Push(Stack &s,ElemType e);
//出棧操作
bool Pop(Stack &s,ElemType &e);
//判斷棧是否爲空
bool Empty(Stack s);
//判斷函數 
bool Check(char *str);

int main(void)
{
	char str[20];
	char c;
	printf("請輸入要判斷的字符串,以#號結束\n");
	int i = 0;
	scanf("%s",str);
	bool result = Check(str);
	if(result)
	{
		printf("匹配成功!");
	}
	else
	{
		printf("匹配失敗!"); 
	}
	return 0;
}

//判斷函數 
bool Check(char *str)
{
	Stack s;
	InitStack(s); //初始化
	int len = strlen(str); //獲取字符串的長度,用來遍歷字符串
	ElemType e;
	for(int i = 0;i<len;i++)
	{
		char a = str[i];
		switch(a)
		{
			case '(':
			case '[':
				Push(s,a);
				break;
			case ')':
				if(Pop(s,e))
				{
					if(e!='(')
					{
						return false; //出棧的元素與循環中的元素不匹配 
					}
				}
				else
				{
					return false;
				}
				break;
			case ']':
				
				if(Pop(s,e))
				{
					if(e!='[')
					{
						return false;
					}
				}	
				else
				{
					return false;
				}
				break;
		}
	} 
	if(Empty(s))
	{
		return true; //如果隊列爲空,則說明完全匹配成功 
	}
	else
	{
		return false;
	} 
}

//初始化棧
void InitStack(Stack &s)
{
	SLink p = (SLink)malloc(sizeof(SNode));
	p->next = NULL;
	s.top = p; //頭節點
	s.count = 0; 
}

//入棧操作
bool Push(Stack &s,ElemType e)
{
	SNode *p = (SNode*)malloc(sizeof(SNode));
	p->data = e;
	p->next = s.top->next;
	s.top->next = p;
	s.count++;
	return true;
} 

//出棧操作
bool Pop(Stack &s,ElemType &e)
{
	if(s.count==0)
	{
		return false;
	}
	SNode *p = s.top->next;
	e = p->data;
	s.top->next = p->next;
	s.count--;
	free(p);
	return true;
} 

//判斷棧是否爲空
bool Empty(Stack s)
{
	if(s.count==0)
	{
		return true;
	}
	else
	{
		return false;
	}
} 


 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章