C语言编程100题-8.2

时间:2025-05-06 20:14:43

8.2
利用字符栈检查表达式的括号是否匹配。
提示:
从左向右扫描表达式,遇到“(”进栈,遇到“)”出栈,扫描完表达式后,若栈空,表示括号匹配。否则,
(1)当扫描完表达式后棧不空,可断定括号是不匹配的
(2)表达式未扫描完,需要出棧时棧是空的,此时可断定括号是不匹配的。
测试样例:
如输入:
(a+b)(5+c)((22-c)/23+56)
则输出:
括号匹配!

输入:
2+(5+8))
输出:
括号不匹配!
样例输入:
((a+b)*(a-b)
样例输出:
括号不匹配!

#include<>
#include<>
#include<>
typedef struct STACK
{
	int*Sarray;
	int top;
	int bottom;
}Stack;
int Push(Stack* stack, int data, int max);
int pop(Stack* stack);
int main()
{
	char a[20];
	Stack *pStack = (Stack*)malloc(sizeof(Stack));
	const int MAX = 100;
	if (pStack) {
		pStack->Sarray = (int*)malloc(sizeof(int) * 5);
		pStack->bottom = 0;
		pStack->top = 0;
	}
	gets(a);
	int i = 0; int e; int h = 0;
	i = strlen(a);
	for (int j = 0; j < i; j++)
	{
		if (a[j] == '(')
		{
			Push(pStack,1,MAX);
		}
		else if (a[j] == ')')
		{
			e=pop(pStack);
			if(e==0)
			{ 
				printf("括号不匹配!");
				h = 1;
			}	
		}
	}
	if (h == 0)
	{
		if(pop(pStack)==0)printf("括号匹配!");
		else printf("括号不匹配!");
	}
	return 0;
}
int Push(Stack* stack, int data, int max) //元素入栈,top上移。如果top=99 已满(栈容量最大100)
{
	if (stack->top == max)
	{
		printf("栈已满\n");
		return 0;
	}
	else
	{
		stack->Sarray[stack->top] = data; stack->top++; return stack->top;
	}
}
int pop(Stack *stack)//元素弹出
{
	if (stack->top > stack->bottom)
	{
		stack->top--;
		return stack->Sarray[stack->top];
	}
	else
		return 0;
}