注册 登录
编程论坛 数据结构与算法

括号的匹配,求大神指导哪里错了,总是会显示缺少右括号

水若寒333 发布于 2014-04-01 23:52, 518 次点击
# include <string.h>
# include <ctype.h>
# include <malloc.h>
# include <limits.h>
# include <stdio.h>
# include <stdlib.h>
# include <io.h>
# include <math.h>
# include <process.h>
# include <iostream.h>
# define TRUE 1
# define FALSE 0
# define OK 1
# define ERROR 0
# define INFEASIBLE -1
typedef int Status;
typedef int Boolean;
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 2
struct SqStack
{
 SElemType *base;
 SElemType *top;
 int stacksize;
};
Status InitStack(SqStack &S)
{
 if(!(S.base=(SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType))))
     exit(OVERFLOW);
 S.top=S.base;
 S.stacksize=STACK_INIT_SIZE;
 return OK;
}
Status StackEmpty(SqStack S)
{
  if(S.top==S.base)
      return OK;
  else
      return ERROR;
 }
Status push(SqStack &S,SElemType e)
{
 if(S.top-S.base>=S.stacksize)
 {
  S.base=(SElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));
  if(!S.base)
      exit(OVERFLOW);
    S.top=S.base+S.stacksize;
    S.stacksize+=STACKINCREMENT;
 }
 *(S.top)++=e;
  return OK;
 
}
Status pop(SqStack &S,SElemType &e)
{
if(S.top==S.base)
return ERROR;
e=*--S.top;
return OK;

}
typedef char SElemType;
#include "c1.h"
#include "c3.h"

void check()
{
    SqStack s;
    SElemType ch[80],*p,e;
    if(InitStack(s))
    {
        printf("请输入表达式\n");
        gets(ch);
        p=ch;
        while(*p)
        {
            switch(*p)
            {  
             case '(':
             case '[':push(s,*p++);break;
             case ')':
             case ']':if(s.base!=s.top  )
                     {
                         pop(s,e);
                         if(e=='['&&*p!=']'||e=='('&&*p!=')')
                         {
                             printf("左右括号不配对\n");
                             exit(ERROR);
                         }
                         else
                         {   p++;
                             break;
                         }
                     }
                     else
                     {
                       printf("缺乏左括号\n");
                       exit(ERROR);
                     }
                     break;
            default:
                p++;
                break;
            }
        
         if(s.base==s.top)
            printf("括号配对\n");
         else
            printf("缺乏右括号\n");
        }
    }
}

void main()
{check();}
2 回复
#2
hubinyes2014-04-02 15:59
#3
不玩虚的2014-04-02 16:47
沙发可以不
1