//采用顺序栈编程实现:表达式的括号是否匹配问题。
//要求:输入带括号的表达式,判断其中括号是否配对。
//扩展功能:给出配对括号的位序和不配对括号的位序。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#define OVERFLOW -2
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define ERROR 0
#define OK 1
using namespace std;
typedef struct
{
char c;
int pos;
} Brack,*Bracket;
typedef struct
{
Bracket base;
Bracket top;
int stacksize;
} SqStack;
int InitStack(SqStack &S)
{
S.base=(Bracket)malloc(STACK_INIT_SIZE*sizeof(Brack));
if(!S.base)
return ERROR;
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}
Brack GetTop(SqStack S,Brack e)
{
if(S.top==S.base)
exit(OVERFLOW);
S.top--;
e=*S.top;
return e;
}
int Push(SqStack &S,Brack e)
{
if(S.top-S.base>=S.stacksize)
{
S.base=(Bracket)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(Brack));
if(!S.base)
exit(OVERFLOW);
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top=e;
S.top++;
return OK;
}
int Pop(SqStack &S, Brack &e)
{
if(S.base==S.top)
return ERROR;
e=*(S.top-1);
S.top--;
return OK;
}
bool equal_e(char a,char b)
{
if(a=='('&&b==')')
return true;
else if(a=='{'&&b=='}')
return true;
else if(a=='['&&b==']')
return true;
else
return false;
}
char ch[100];
int match[100];
int nomatch[100];
int p=0,q=0;
bool find_brack(SqStack S,char e)
{
int flag=0;
while(S.base!=S.top)
{
S.top--;
if(equal_e(S.top->c,e))
{
flag=1;
match[p++]=S.top->pos;
break;
}
}
if(flag==1)
return true;
else
return false;
}
void fun()
{
SqStack S;
InitStack(S);
Brack b;
for(int i=0; i<strlen(ch); i++)
{
if(ch[i]=='{'||ch[i]=='('||ch[i]=='[')
{
b.c=ch[i];
b.pos=i+1;
Push(S,b);
}
//GetElem(S);
if(ch[i]=='}'||ch[i]==')'||ch[i]==']')
{
if(find_brack(S,ch[i]))
{
do
{
Pop(S,b);
if(equal_e(b.c,ch[i]))
{
break;
}
else
{
nomatch[q++]=b.pos;
}
}
while(true);
}
else
{
nomatch[q++]=i+1;
//cout<<"fun"<<i+1<<endl;
}
}
}
while(S.base!=S.top)
{
Pop(S,b);
nomatch[q++]=b.pos;
}
if(q!=0)
{
cout<<"括号匹配失败!"<<endl;
if(p!=0)
{
cout<<"匹配成功的括号位序是:"<<endl;
sort(match,match+p);
for(int i=0; i<p; i++)
{
cout<<match[i]<<" ";
}
cout<<endl;
}
cout<<"匹配不成功的括号位序是:"<<endl;
sort(nomatch,nomatch+q);
for(int i=0; i<q; i++)
{
cout<<nomatch[i]<<" ";
}
cout<<endl;
cout<<"注:这里的位序是指括号在表达式中的位置顺序!"<<endl;
}
else
{
cout<<"表达式中的括号均是配对的。"<<endl;
}
}
int main()
{
cin>>ch;
fun();
return 0;
}
顺序栈实现括号匹配
最新推荐文章于 2022-10-11 20:31:58 发布