数据结构课程设计之括号匹配
程序员文章站
2022-04-02 23:12:50
...
题目
括号匹配问题,假设一个算术表达式中包含圆括号、方括号和花括号三种类型的括号,编写一个函数,用来判别表达式中括号是否正确匹配
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef char SElemType;
#define OK 0
#define ERROR 1
#define OVERFLOW -2
typedef int Status;
typedef struct
{
SElemType *base;
SElemType *top;
Status stacksize;
}SqStack;
Status InitStack(SqStack* S)
{
S->base =(char*)malloc(sizeof(SElemType) * MAXSIZE);
if( !S->base ) return OVERFLOW;
S->top = S->base;
S->stacksize = MAXSIZE;
return OK;
}
Status StackLength( SqStack S )
{
return S.top - S.base;
}
Status Push( SqStack* S, SElemType e)
{
if( S->top - S->base== S->stacksize )
return ERROR;
*S->top++=e;
return OK;
}
SElemType Pop( SqStack* S, SElemType e)
{
if( S->top == S->base )
{
return 'w';
}
e=*--S->top;
return e;
}
Status DestroyStack( SqStack* S )
{
if( S->base )
{
free(S->base);
S->stacksize = 0;
S->base = S->top = NULL;
}
return OK;
}
Status isLeft(char c)
{
Status ret = 0;
switch(c)
{
case '(':
case '[':
case '<':
case '{':
case '\'':
case '\"':
ret = 1;
break;
default:
ret = 0;
break;
}
return ret;
}
Status isRight(char c)
{
Status ret = 0;
switch(c)
{
case ')':
case ']':
case '>':
case '}':
case '\'':
case '\"':
ret = 1;
break;
default:
ret = 0;
break;
}
return ret;
}
Status match(char left, char right)
{
Status ret = 0;
switch(left)
{
case '(':
ret = (right == ')');
break;
case '[':
ret = (right == ']');
break;
case '<':
ret = (right == '>');
break;
case '{':
ret = (right == '}');
break;
case '\'':
ret = (right == '\'');
break;
case '\"':
ret = (right == '\"');
break;
default:
ret = 0;
break;
}
return ret;
}
Status judge(const char* code)
{
SqStack stack;
InitStack(&stack);
Status ret=0;
Status i=0;
while( code[i] != '\0')
{
if(isLeft(code[i]))
{
Push(&stack,code[i]);
}
else if(isRight(code[i]))
{
char c = Pop(&stack,*(stack.top));
if(c=='w' || !match(c,code[i]))
{
printf("%c 匹配失败!\n",code[i]);
break;
}
}
i++;
}
if((StackLength(stack)==0)&&(code[i]=='\0'))
{
printf("成功!\n");
ret = 1;
}
else if((StackLength(stack)!=0))
{
printf("左括号有多余,匹配失败\n");
ret = 0;
}
DestroyStack(&stack);
return ret;
}
int main()
{
printf("进入匹配查询,******* \n");
char* str = (char*)malloc(sizeof(char)*MAXSIZE) ;
scanf("%s",str);
judge(str);
free(str);
}
文档在这里,需要的小伙伴可以拿去参考一下
(里面有两个选题,因为我们老师当初就是让我们做两个选题的)
????????????????????
链接:https://pan.baidu.com/s/1m83uA6DoLkxoF_H9947uJA
提取码:hb18
下一篇: 第五章习题总结