假设表达式中包含三种括号:圆括号( )、方括号[ ]和花括号{},并且它们可以任意嵌套。
例如{[()]()[{}]}或[{()}([])]等为正确格式,而{[}()]或[({)]为不正确的格式。
输入可以是任意表达式,但只对三种括号的匹配情况进行处理判断,如不匹配,给出错误提示。
输入:[(3+4)*{5}-3]
输出:true
输入:[{3+6[}(3+5)]
输出:required ‘]’
输入:{}())]
输出:required ‘(‘
程序完整代码:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define MaxSize 100
typedef struct {
char data[MaxSize];
int top;
}SeqStack;
typedef char DataType;
void InitStack(SeqStack* S);//初始化栈
int GetTop(SeqStack S, DataType* x);
int Push(SeqStack* S, DataType x); //进栈
int Pop(SeqStack* S, DataType* x);//出栈
int IsEmpty(SeqStack* S);
void InitStack(SeqStack* S)//初始化栈
{
S->top = 0;//初始化一个空栈:初始化栈顶下标值,top=0表示该栈为空栈
}
int IsEmpty(SeqStack* S)//判空
{
//判断顺序堆栈S非空否
if (S->top <= 0)
return TRUE;//栈空返回1
else
return FALSE;//非空返回0
}
int Push(SeqStack* S, DataType x) //进栈
{
//把x存入顺序堆栈S中,若入栈成功则返回TRUE,失败返回FALSE
if (S->top >= MaxSize)//判断栈满
{
printf("堆栈已满无法插入! \n");
return FALSE;
}
else
{
S->top++;//指针加1,放元素, return
S->data[S->top - 1] = x;
return TRUE;
}
}
int GetTop(SeqStack S, DataType* x) //取栈顶元素
{
//取顺序堆栈S的当前栈顶元素,由参数x带回
//成功返回TRUE,失败返回FALSE
if (S.top <= 0)//失败情况:栈空,无元素可取
{
printf("堆栈已空,无元素可取! \n");
return FALSE;
}
else//栈非空,取元素,减指针,return
{
*x = S.data[S.top - 1];
return TRUE;
}
}
int Pop(SeqStack* S, DataType* x)//出栈
{
//取出顺序栈顶S的栈顶元素,由参数x带回
//出栈成功返回TRUE,失败返回FALSE
//失败情况:栈空,无元素可出栈
if (S->top <= 0)
{
printf("堆栈已空无法出栈! \n");
return FALSE;
}
else//栈非空,取元素,减指针,return
{
S->top--;
*x = S->data[S->top];
return TRUE;
}
}
void ExpIsCorrect(char exp[], int n)
{
SeqStack MyStack;
int i;
char c;
DataType d;
InitStack(&MyStack);
for (i=0; i < n; i++)
{
if ((exp[i] == '(') ||( exp[i] == '[') || (exp[i] == '{'))
{
Push(&MyStack, exp[i]);
}//括号入栈
else if (exp[i] == ')' && IsEmpty(&MyStack)==0 && GetTop(MyStack, &c) && c == '(')
{
Pop(&MyStack, &d);//匹配成功出栈
}
else if (exp[i] == ')' && IsEmpty(&MyStack) == 0 && GetTop(MyStack, &c) && c != '(')
{
if (c == '[')
printf("required ']' \n");
else
printf("required '}' \n");
return;
}
else if (exp[i] == ']' && IsEmpty(&MyStack) == 0 && GetTop(MyStack, &c) && c == '[')
{
Pop(&MyStack, &d);//匹配成功出栈
}
else if (exp[i] == ']' && IsEmpty(&MyStack) == 0 && GetTop(MyStack, &c) && c != '[')
{
if (c == '(')
printf("required ')' \n");
else
printf("required '}' \n");
return;
}
else if (exp[i] == '}' && IsEmpty(&MyStack) == 0 && GetTop(MyStack, &c) && c == '{')
{
Pop(&MyStack, &d);//匹配成功出栈
}
else if (exp[i] == '}' && IsEmpty(&MyStack) == 0 && GetTop(MyStack, &c) && c != '{')
{
if(c=='[')
printf("required ']' \n");
else
printf("required ')' \n");
return;
}
else if ((exp[i] == ')')&& IsEmpty(&MyStack)==1)
{
printf("required '( '\n");
return;
}
else if ((exp[i] == ']') && IsEmpty(&MyStack) == 1)
{
printf("required '['\n");
return;
}
else if ( (exp[i] == '}')&& IsEmpty(&MyStack) == 1)
{
printf("required '{ '\n");
return;
}
}
if(IsEmpty(&MyStack) == 1)
{
printf("ture\n");
}
}
int main(void)
{
char a[MaxSize];
printf("请输入一个字符串: ");
gets(a);
int n = strlen(a);
ExpIsCorrect(a, n);
}
程序运行结果: