请编写程序检查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<stdlib.h>
#include<stdio.h>
#include<string>
#define STACK_SIZE 101
using namespace std;
typedef char SElemType;
char c;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
int CreatS(SqStack &S)
{
S.base = (SElemType *)malloc(STACK_SIZE*sizeof(SElemType));
if(!S.base)
exit(-1);
S.top=S.base;
S.stacksize = STACK_SIZE;
return 1;
}//创建一个空栈
int Push(SqStack &S,SElemType e)//把元素e放入栈顶
{
if(S.top-S.base>=S.stacksize)
{
return 0;
}
*S.top++=e;
return 1;
}
int Pop(SqStack &S)//删除栈顶元素
{
if(S.top==S.base)
return 0;
S.top--;
return 1;
}
int Empty(SqStack &S)//判断栈是否为空
{
if(S.top==S.base)
return 1;
else
return 0;
}
int main()
{
SqStack S;
CreatS(S);
char s[105];
int f=1,i=0;
while(cin>>s)//一行一行进行输入
{
if(s[0]=='.'&&s[1]=='\0')//结束语句
{
break;
}
for(i=0;s[i]!='\0';i++)
{
if(s[i]=='('||s[i]=='{'||s[i]=='[')//左括号,入栈
{
Push(S,s[i]);
}
else if(s[i]=='/'&&s[i+1]=='*')//左注释(/*),入栈,入栈元素为*
{
Push(S,'*');
i=i+1;
}
else if(s[i]=='*'&&s[i+1]=='/')//若为右注释
{
if(*(S.top-1)=='*')//如果栈顶元素是*,删除栈顶元素
Pop(S);
else
{
c=s[i];
f=0;break;//匹配失败,结束循环
}
i=i+1;
}
else if(s[i]==')'||s[i]=='}'||s[i]==']')//如果是右括号
{
if(s[i]==')'&&!Empty(S)&&*(S.top-1)=='(')
{
Pop(S);
}
else if(s[i]=='}'&&!Empty(S)&&*(S.top-1)=='{')
{
Pop(S);
}
else if(s[i]==']'&&!Empty(S)&&*(S.top-1)=='[')
{
Pop(S);
}
else//没有与之对应的左括号(右括号多)
{
c=s[i];
f=0;
break;
}
}
}
}
if(S.top!=S.base)//左括号多
{
f=0;
}
if(f)
cout<<"YES"<<endl;
else
{
cout<<"NO"<<endl;
if(!Empty(S))
{
if(*(S.top-1)=='(')
cout<<'('<<'-'<<'?'<<endl;
else if(*(S.top-1)=='[')
cout<<'['<<'-'<<'?'<<endl;
else if(*(S.top-1)=='{')
cout<<'{'<<'-'<<'?'<<endl;
else if(*(S.top-1)=='*')
cout<<'/'<<'*'<<'-'<<'?'<<endl;
}
else
{
if(c==')')
cout<<'?'<<'-'<<')'<<endl;
else if(c==']')
cout<<'?'<<'-'<<']'<<endl;
else if(c=='}')
cout<<'?'<<'-'<<'}'<<endl;
else if(c=='*')
cout<<'?'<<'-'<<'*'<<'/'<<endl;
}
}
return 0;
}