括号表达式

来源:互联网 发布:外汇程序化交易软件 编辑:程序博客网 时间:2024/05/15 01:42
#include<cstdio>
#include<cstring>
char str[10001],str2[10001];
class Stack
{
public:
Stack();
int Pop();
void Push(char c);
char GetTop();
int Getlen();
bool Empty();
private:
int top;
char ch[10001];
};
Stack::Stack()
{
top=-1;
memset(ch,'/0',sizeof(ch));
}
void Stack::Push(char c)
{
ch[++top]=c;
}
int Stack::Pop()
{
return ch[top--];
}
char Stack::GetTop()
{
return ch[top];
}
int Stack::Getlen()
{
return top;
}
bool Stack::Empty()
{
if(top==-1) return true;
else return false;
}
int main()


{
Stack s;
int i,k,j,len;
while(scanf("%s",&str)!=EOF)
{
memset(str2,'/0',sizeof(str2));
len=strlen(str);
for(i=0;i<len;i++)
{
if(s.Empty()) s.Push(str[i]);
else if(str[i]==')'&&s.GetTop()=='(')
s.Pop();
else s.Push(str[i]);
}
if(s.Empty())
{
for(j=0;j<len;j++)
printf("%c",str[j]);
printf("/n");
}
else
{
k=2*s.Getlen()+2;
for(i=0;i<=k/2-1;i++)
{
str2[i]=s.Pop();
}
for(i=k/2-1;i>=0;i--)
printf("%c",str2[i]);
printf("/n");
for(i=0;i<k/2-1;i++)
if(str2[i]!=str2[i+1]) break;
if(i==k/2-1)
{
if(str2[0]=='(')
{
for(j=i;j>=0;j--)
printf("%c",str2[j]);
for(j=0;j<=k/2-1;j++)
printf(")");
printf("/n");
}
else
{
for(j=0;j<=k/2-1;j++)
printf("(");
for(j=i;j>=0;j--)
printf("%c",str2[j]);
printf("/n");
}
}
else
{
for(j=k/2-1;j>i;j--)
printf("(");
for(j=k/2-1;j>=0;j--)
printf("%c",str2[j]);
for(j=0;j<=i;j++)
printf(")");
printf("/n");
}
}
memset(str,'/0',sizeof(str));
}
return 0;

}