错误的括号代码

来源:互联网 发布:cad看图软件mac版免费 编辑:程序博客网 时间:2024/06/07 08:50

#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
typedef char ElemType;
typedef struct
{
    ElemType data[MaxSize];
    int top;                //栈指针
} SqStack;                  //顺序栈类型定义

 


void InitStack(SqStack *&s);    //初始化栈
void DestroyStack(SqStack *&s);  //销毁栈
bool StackEmpty(SqStack *s);     //栈是否为空
int StackLength(SqStack *s);  //返回栈中元素个数——栈长度
bool Push(SqStack *&s,ElemType e); //入栈
bool Pop(SqStack *&s,ElemType &e); //出栈
bool GetTop(SqStack *s,ElemType &e); //取栈顶数据元素
void DispStack(SqStack *s);  //输出栈
bool Match(char exp[]);

 


void InitStack(SqStack *&s)
{
    s=(SqStack *)malloc(sizeof(SqStack));
    s->top=-1;
}
void DestroyStack(SqStack *&s)
{
    free(s);
}
int StackLength(SqStack *s)  //返回栈中元素个数——栈长度
{
    return(s->top+1);
}
bool StackEmpty(SqStack *s)
{
    return(s->top==-1);
}
bool Push(SqStack *&s,ElemType e)
{
    if (s->top==MaxSize-1)    //栈满的情况,即栈上溢出
        return false;
    s->top++;
    s->data[s->top]=e;
    return true;
}
bool Pop(SqStack *&s,ElemType &e)
{
    if (s->top==-1)     //栈为空的情况,即栈下溢出
        return false;
    e=s->data[s->top];
    s->top--;
    return true;
}
bool GetTop(SqStack *s,ElemType &e)
{
    if (s->top==-1)         //栈为空的情况,即栈下溢出
        return false;
    e=s->data[s->top];
    return true;
}

void DispStack(SqStack *s)  //输出栈
{
    int i;
    for (i=s->top;i>=0;i--)
        printf("%c ",s->data[i]);
    printf("\n");
}


bool Match(char exp[])
{
    int  i;
    char e;
 bool match=true;
    SqStack *st;
    InitStack(st); 
 for(i=0; exp[i]!='\0'&&match; i++)
 {
  if(exp[i]=='('||exp[i]=='['||exp[i]=='{')
   Push(st,exp[i]);
  else if(exp[i]==')'||exp[i]==']'||exp[i]=='}')
  {
   if(GetTop(st,e)==true)
   {
    if(exp[i]=='('&&e=='(')
     
    {
     match=true;
     Pop(st,e);
    }
    else match=false;
    if(exp[i]=='['&&e=='[')
     
    {
     match=true;
     Pop(st,e);
    }
    else match=false;
    if(exp[i]=='{'&&e=='{')
    {
     match=true;
     Pop(st,e);
    }
    else match=false;  
   }
  }
 }
 if(!StackEmpty(st))
  match=false;
 DestroyStack(st);

 return match; 
}
int main()
{

    char exp[50];
    printf("请输入表达式:");
    scanf("%exp", exp);
    if(Match(exp))
        printf("配对正确!!\n");
    else
        printf("配对错误!!\n");
    return 0;
}

错误之处:

 

0 0
原创粉丝点击