请编写程序检查C语言源程序中下列符号是否配对:/* 与 */、(与)、[与]、{与}。
输入格式:
输入为一个C语言源程序。当读到某一行中只有一个句点.和一个回车的时候,标志着输入结束。程序中需要检查配对的符号不超过100个。
输出格式:
首先,如果所有符号配对正确,则在第一行中输出YES,否则输出NO。然后在第二行中指出第一个不配对的符号:如果缺少左符号,则输出?-右符号;如果缺少右符号,则输出左符号-?。
输入样例1:
void test()
{
int i, A[10];
for (i=0; i<10; i++) /*/
A[i] = i;
}
输出样例1:
NO
/*-?
输入样例2:
void test()
{
int i, A[10];
for (i=0; i<10; i++) /**/
A[i] = i;
}]
.
输出样例2:
NO
?-]
输入样例3:
void test()
{
int i
double A[10];
for (i=0; i<10; i++) /**/
A[i] = 0.1*i;
}
.
输出样例3:
YES
代码如下:
#include<iostream>
#include<stdio.h>
#include<string>
#define MAXSIZE 100
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
using namespace std;
char c;
typedef struct
{
char *base;
char *top;
int stacksize;
} SqStack;
Status InitStack(SqStack &S)
{
S.base=new char[MAXSIZE];
if(!S.base)
return OVERFLOW;
S.top=S.base;
S.stacksize=MAXSIZE;
return OK;
}
Status push(SqStack &S,char e)
{
if(S.top-S.base==S.stacksize)
return ERROR;
*S.top++=e;
return OK;
}
Status pop(SqStack &S,char e)
{
if(S.top==S.base)
return ERROR;
e=*--S.top;
return OK;
}
char GetTop(SqStack S)
{
if(S.top!=S.base)
{
return *(S.top-1);
}
}
bool StackEmpty(SqStack &S)
{
if(S.top==S.base)
return true;
else
return false;
}
bool Matching(SqStack &S)
{
int flag=1,t=1,i;
char str[1000];
while(gets(str))
{
if(str[0]=='.'&&str[1]==0)
break;
for(i=0; str[i]!='\0'; i++)
{
if(str[i]=='('||str[i]=='['||str[i]=='{')
push(S,str[i]);
if(str[i]=='/'&&str[i+1]=='*')
{
push(S,str[i]);
push(S,str[i+1]);
i+=2;
}
if(str[i]==')')
{
if(!StackEmpty(S)&&GetTop(S)=='(')
pop(S,'(');
else
{
c=str[i];
flag=0;
break;
}
}
if(str[i]==']')
{
if(!StackEmpty(S)&&GetTop(S)=='[')
pop(S,'[');
else
{
c=str[i];
flag=0;
break;
}
}
if(str[i]=='}')
{
if(!StackEmpty(S)&&GetTop(S)=='{')
pop(S,'{');
else
{
c=str[i];
flag=0;
break;
}
}
if(str[i]=='*'&&str[i+1]=='/')
{
if(!StackEmpty(S)&&GetTop(S)=='*')
{
pop(S,'*');
if(!StackEmpty(S)&&GetTop(S)=='/')
pop(S,'/');
else
{
c=str[i];
flag=0;
break;
}
}
else
{
c=str[i];
flag=0;
break;
}
}
/*if(StackEmpty(S))
{
if(str[i]==')'||str[i]=='}'||str[i]==']')
{
c=str[i];
t=0;
}
else if(str[i]=='*'&&str[i+1]=='/')
{
c=str[i];
t=0;
}
//cout<<c<<endl;
}*/
}
}
if(StackEmpty(S)&&(flag==1))
return true;
else
return false;
}
int main()
{
SqStack A;
InitStack(A);
if(Matching(A))
cout<<"YES"<<endl;
else
{
cout<<"NO"<<endl;
if(!StackEmpty(A))
{
if(GetTop(A)=='(')
cout<<'('<<'-'<<'?'<<endl;
else if(GetTop(A)=='[')
cout<<'['<<'-'<<'?'<<endl;
else if(GetTop(A)=='{')
cout<<'{'<<'-'<<'?'<<endl;
else if(GetTop(A)=='*')
cout<<'/'<<'*'<<'-'<<'?'<<endl;
}
else
{
if(c==')')
cout<<'?'<<'-'<<')'<<endl;
else if(c==']')
cout<<'?'<<'-'<<']'<<endl;
else if(c=='}')
cout<<'?'<<'-'<<'}'<<endl;
else if(c=='*')
cout<<'?'<<'-'<<'*'<<'/'<<endl;
}
}
}