输入一串字符查看括号是否匹配

//输入字符串查看括号是否匹配···
#include
#include
#include
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
using namespace std;
typedef struct
{
 int *base;
 int *top;
 int stracksize;
}SqStack;
int InitStack(SqStack &S)
{
 S.base=(int *)malloc(STACK_INIT_SIZE*sizeof(int));
 if(!S.base)
  exit(ERROR);
 S.top=S.base;
 S.stracksize=STACK_INIT_SIZE;
 return OK;
}
int Push(SqStack &S,char e)
{
 *S.top++=e;
 return OK;
}
int Pop(SqStack &S,char &e)
{
 if(S.base!=S.top)
 {
  e=*--S.top;
      return OK;
 }
 else
  return ERROR;
}
int pipei(SqStack S,char ch)
{
    switch(ch)
 {
 case '}':if(*--S.top=='{') return OK;
 case ']':if(*--S.top=='[') return OK;
 case ')':if(*--S.top=='(') return OK;
 }
 return ERROR;
}
int Choose(char ch[20])
{
 char ch1[20];
 int i=0,j=0;
 strcpy(ch1,ch);
    int num=strlen(ch);
    while(*(ch1+j)!='\0')
    {
      if(*(ch1+j)=='{'||*(ch1+j)=='}'||*(ch1+j)=='['||*(ch1+j)==']'||*(ch1+j)=='('||*(ch1+j)==')')
   {
    ch[i]=ch1[j];
    i++;
      } 
   j++;
    } ch[i]='\0';
 return OK;
}
int show(SqStack &S)
{
char ch[20],*ch1;
 cout<<"请输入括号字符:";
 cin>>ch;
 Choose(ch);
 ch1=ch;
 Push(S,*ch1);
 while(*ch1!='\0')
 {
  ch1++;
  if(*ch1=='\0')
   break;
  if(pipei(S,*ch1))
   Pop(S,*ch1);
  else
   Push(S,*ch1);
 }
 if(S.base==S.top)
  cout<<"括号匹配!!!"<<endl;
 else
  cout<<"括号不匹配!!!"<<endl;
 return OK;
}
int main()
{
 SqStack S;
 InitStack(S);
 show(S);
 return 0;
}

posted on 2012-12-07 22:33  木本  阅读(203)  评论(0编辑  收藏  举报

导航