Chinaunix首页 | 论坛 | 博客

分类: C/C++

2012-09-04 21:16:52

 此括号的匹配是({[]}) 匹配成功, ({}))错误。。



#include

#define stack_size  50
#define stackelem   char


typedef struct 
{
stackelem elem[stack_size];
int  top;
}seqstack;

/*初始化一个栈*/
void initstack (seqstack *s)
{
   s->top = -1;
}
int push (seqstack *s,stackelem x)
{
if (s->top == stack_size -1)
return  -1;
s->top ++;
s->elem[s->top] = x;
return 0;
}
int pop (seqstack *s,stackelem *x)
{
if (s->top == -1)
return -1;
else 
{
*x = s->elem [s->top];
s->top --;
return 0;
}

}
int  emply(seqstack *s)
{
 if (s->top == -1)
return  1;
 else 
return 0;
}

int gettop (seqstack *s,stackelem *x)
{
if (s->top == -1)
return -1;
else 
*x= s->elem [s->top];
    
return 0;
}
int  match1 (char  ch ,char str)
{
if (ch == '(' && str == ')')  return 1;
if (ch == '{'&& str == '}')  return 1;
     if (ch == '['&& str == ']')   return 1;
 

}


void match (char *str)
{
seqstack s;
int i;
char ch;

initstack (&s);

for (i = 0;str[i]!='\0';i++)
{
switch (str[i])
{
case'(':
case'[':
case'{':
push (&s,str[i]);
break;
case')':
case']':
case'}':
if (emply (&s))
{
printf ("\n 右括号多余!");
return  ;
}
else
{
gettop (&s,&ch);
if (match1(ch ,str[i]))
    pop (&s,&ch);
else 
{
printf ("\n 对应的左右括号不同类!");
return ;
}
}

}
}

if (emply (&s))
printf ("\n括号匹配!");
else 
printf ("\n 做括号多余!");
}


int main ()
{
char str[100];
printf ("请输入括号:");
scanf ("%s",str);
match (str);

}
阅读(1242) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~