数据结构8,栈的应用--括号匹配

该代码实现了一个简单的括号匹配算法,通过使用栈数据结构来检查字符串中的括号是否正确配对。在遍历字符串时,遇到左括号则压栈,遇到右括号则尝试匹配栈顶的左括号。最后栈内应仅剩初始压入的#字符,表示所有括号已匹配。
摘要由CSDN通过智能技术生成

整体思路
输入一个字符串,从第一个到最后一个字符,当遇到‘{’ ‘[’ ‘(‘的时候就将其压入栈中,在遇到其它字符时,看是否匹配,如果是’}’ ‘]’ ')'的话就与对应的 ’{‘ ‘[’ ‘(‘相抵消,出栈。处理完所有的括号时,栈内还剩余’#’。最后出现的左括号最后匹配。
代码如下

//括号匹配
#include<stdio.h>
#include<malloc.h> 

#define STACK_MAX_SIZE 10

/**
 *Linear stack of integers.The key is datas.
 */
typedef struct CharStack
{
	int top;
	int data[STACK_MAX_SIZE];//The maximum lengt is fixed.
} *CharStackPtr;

/*
 *函数申明
 */
void outputStack(CharStackPtr paraStack);
CharStackPtr charStack_Init();
void push(CharStackPtr paraStackPtr, int paravalue);
char pop(CharStackPtr paraStackPtr);
void pushPop_Test();
bool bracketMatching(char*paraString, int paraLength);
void bracketMatching_Test();
/**
 *Output the stack.
 */
void outputStack(CharStackPtr paraStack)
{
	for(int i=0; i <= paraStack->top; i++)
	{
		printf("%c ", paraStack->data[i]);
	}//of for i
	printf("\n");
}//of OutputStack

/**
 * Initialize an empty char stack. No error checking for this function.
 * @param paraStackPtr The pointer to the stack. It must be a pointer to change the stack.
 * @param paraValues An int array storing all elements.
 */
CharStackPtr charStack_Init()
{
	CharStackPtr resultPtr = (CharStackPtr)malloc(sizeof(struct CharStack));
	resultPtr->top = -1;
	
	return resultPtr;
}//of CharStack_Init

/**
 * Push an element to the stack.
 * @param paraValue The value to be pushed.
 */
void push(CharStackPtr paraStackPtr, int paraValue)
{
	//step1.Space check.
	if(paraStackPtr->top >= STACK_MAX_SIZE - 1)
	{
		printf("Cannot push element: stack full\n");
		return;
	}//of if
	
	//step2.Update the top.
	paraStackPtr->top++;
	
	//step3.Push element.
	paraStackPtr->data[paraStackPtr->top] = paraValue;
}//of push

/**
 * Pop an element from the stack.
 * @return The popped value.
 */
char pop(CharStackPtr paraStackPtr)
{
	//step1.Space check;
	if(paraStackPtr->top < 0)
	{
		printf("Cannot pop element: stack empty\n");
		return '\0';
	}//of if
	
	//step2.Update the top.
	paraStackPtr->top--;
	
	//step3.Pop element.
	return paraStackPtr->data[paraStackPtr->top + 1];
}//of pop

/**
 *Test the push function.
 */
void pushPop_Test()
{
	printf("----pushPop_Test begins.----\n");
	char ch;
	
	//Initialize.
	CharStackPtr tempStack = charStack_Init();
	printf("After initialization, the stack is: ");
	outputStack(tempStack);
	
	//Push.
	for(char ch = 'a'; ch < 'm'; ch++)
	{
		printf("Pushing %c.\n", ch);
		push(tempStack, ch);
		outputStack(tempStack);
	}//of for i
	
	printf("----pushPop_Test ends.----\n");
}//of pushPop_Test

/**
 * Is the bracket matching?
 * 
 * @param paraString The given expression.
 * @return Match or not.
 */
bool bracketMatching(char*paraString, int paraLength)
{
	//step1.Initialize the stack through pushing a '#' at the bottom.
	CharStackPtr tempStack = charStack_Init();
	push(tempStack, '#');
	char tempChar, tempPopedChar;
	
	//step2.Process the string.
	for(int i =0; i < paraLength; i++)
	{
		tempChar = paraString[i];
		
		switch(tempChar)
		{
			case '(':
			case '[':
			case '{':
				push(tempStack, tempChar);
				break;
			case ')':
				tempPopedChar = pop(tempStack);
				if(tempPopedChar != '(')
				{
					return false;
				}//of if
				break;
			case ']':
				tempPopedChar = pop(tempStack);
				if(tempPopedChar != '[')
				{
					return false;
				}//of if
				break;
			case '}':
				tempPopedChar = pop(tempStack);
				if(tempPopedChar != '{')
				{
					return false;
				}//of if
				break;
			default :
				break;
		}//of switch
	}//of for i
	tempPopedChar = pop(tempStack);
		if (tempPopedChar != '#') 
		{
			return true;
		} // Of if

		return true;
}//of bracketMatching;

/**
 * Unit test.
 */
void bracketMatching_Test()
{
	char* tempExpression = "[2 + (1 - 3)] * 4";
	bool tempMatch = bracketMatching(tempExpression, 17);
	printf("Is the expression '%s' bracket matching ? %d\n", tempExpression, tempMatch);
	
	tempExpression = "( )  )";
	tempMatch = bracketMatching(tempExpression, 6);
	printf("Is the expression '%s' bracket matching? %d \n", tempExpression, tempMatch);

	tempExpression = "()()(())";
	tempMatch = bracketMatching(tempExpression, 8);
	printf("Is the expression '%s' bracket matching? %d \n", tempExpression, tempMatch);

	tempExpression = "({}[])";
	tempMatch = bracketMatching(tempExpression, 6);
	printf("Is the expression '%s' bracket matching? %d \n", tempExpression, tempMatch);


	tempExpression = ")(";
	tempMatch = bracketMatching(tempExpression, 2);
	printf("Is the expression '%s' bracket matching? %d \n", tempExpression, tempMatch);
}//of bracketMatching_Test
/**
 The entrance.
 */
int main()
{
	bracketMatching_Test();
	return 0;
}//of main

代码初始化
动态分配一个栈,只压入top是-1,data为空的

CharStackPtr charStack_Init()
{
	CharStackPtr resultPtr = (CharStackPtr)malloc(sizeof(struct CharStack));
	resultPtr->top = -1;
	
	return resultPtr;
}

遍历
i从0开始直到i等于top,打印出data[i]

void outputStack(CharStackPtr paraStack)
{
	for(int i=0; i <= paraStack->top; i++)
	{
		printf("%c ", paraStack->data[i]);
	}//of for i
	printf("\n");
}

压栈
首先对空间检查,看栈有没有满
top++,给data[top]赋值,将数据压入栈

void push(CharStackPtr paraStackPtr, int paraValue)
{
	//step1.Space check.
	if(paraStackPtr->top >= STACK_MAX_SIZE - 1)
	{
		printf("Cannot push element: stack full\n");
		return;
	}//of if
	
	//step2.Update the top.
	paraStackPtr->top++;
	
	//step3.Push element.
	paraStackPtr->data[paraStackPtr->top] = paraValue;
}//of push

出栈
检查栈是否为空,为空不能出栈
不为空,top–,弹出data[top+1]

char pop(CharStackPtr paraStackPtr)
{
	//step1.Space check;
	if(paraStackPtr->top < 0)
	{
		printf("Cannot pop element: stack empty\n");
		return '\0';
	}//of if
	
	//step2.Update the top.
	paraStackPtr->top--;
	
	//step3.Pop element.
	return paraStackPtr->data[paraStackPtr->top + 1];
}//of pop

运行结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值