1. 程式人生 > >C語言中利用棧檢測括號是否匹配

C語言中利用棧檢測括號是否匹配

檢測括號是否匹配的演算法中,棧的特性是最符合括號特點的。棧的先進後出將括號的匹配正好完美實現。

思想:

從字串開頭向後逐個檢測,檢測到除括號外的元素就跳過。檢測到左括號時,就進行入棧操作,繼續向後檢測。檢測到有括號時,就檢查棧頂元素是否是匹配的左括號。若不匹配,則直接返回錯誤訊號,使程式結束;若匹配,進行出棧操作,繼續向後檢測。結束時,要判斷棧是否為空,若不為空,則括號不匹配;若為空,則括號匹配。

程式碼:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define	 STA_SIZE	50//棧的大小
#define	 BUF_SIZE	50//輸入字串的大小

//棧的宣告
struct stack{
	char sta[STA_SIZE];
	int top;
};
//判斷棧是否為空
int if_empty(struct stack* psta)
{
	if(psta->top == -1)
		return 0;
	else
		return 1;
}
判斷棧是否為滿
int if_full(struct stack* psta)
{
	if(psta->top == STA_SIZE - 1)
		return 1;
	else 
		return 0;
}
//初始化棧
void init_stack(struct stack* psta)
{
	psta->top = -1;
	bzero(psta->sta, sizeof(char)*STA_SIZE);
}
//入棧操作
int push_stack(struct stack* psta, char data)
{
	if(if_full(psta)){
		printf("stack is full. \n");
		exit(1);
	}
	(psta->top)++;
	psta->sta[psta->top] = data;
}
//出棧操作
char pop_stack(struct stack* psta)
{
	if(if_empty(psta) == 0){
		printf("stack is empty. \n");
		exit(1);
	}
	char tmp = psta->sta[psta->top];
	(psta->top)--;
	
	return tmp;
}
//檢視棧頂元素
char get_top_data(struct stack* psta)
{
	if(if_empty(psta) == 0){
		return -1;
	}
	char tmp = psta->sta[psta->top];

	return tmp;
}
//括號匹配函式
int bracket_match(struct stack* sta, char* string)
{
	char* ps = string;
	while(*ps != '\0'){
		switch (*ps) {
			case '(':
			case '{':
			case '[':
			case '<': 
				push_stack(sta, *ps);		
				break;
			case ')':
				if ('(' == (get_top_data(sta)))	{	
					pop_stack(sta);
					break;
				} else 
					goto err; 
			case '}':
				if ('{' == (get_top_data(sta)))	{
					pop_stack(sta);
					break;
				} else 
					goto err; 
			case ']':
				if ('[' == (get_top_data(sta)))	{
					pop_stack(sta);
					break;
				} else 
					goto err; 
			case '>':
				if ('<' == (get_top_data(sta)))	{
					pop_stack(sta);
					break;
				} else 
					goto err; 
			default:
				 break;
		}
		ps++;
	}	
	if(if_empty(sta) == 0)
ok:
		return 0;
	else 
err:
		return 1;
}
int main(int argc, char* argv[])
{
	struct stack sta;

	init_stack(&sta);	

	char buf[BUF_SIZE] = {0};	

//	char* buf = "he({ljfs})jfkdjs";
	printf("請輸入要檢測的不超過50個字元的字串:\n");
	fgets(buf, BUF_SIZE, stdin);

	int ret = bracket_match(&sta, buf);	
	if(ret == 0)
		printf("括號檢測匹配... \n");
	else
		printf("括號檢測不匹配... \n");
		
	return 0;
}

結果: