一个逆波兰式的生成程序VC & C++
你学过C,应该能看懂吧?
#include<iostream.h>
#include<string.h>
#include<math.h>
#include<ctype.h>
#define maxbuffer 64
void main()
\{
char display_out(char out_ch[maxbuffer], char ch[32]);
//int caculate_array(char out_ch[32]);
static int i=0;
static int j=0;
char ch[maxbuffer],s[maxbuffer],out[maxbuffer];
cout<<"请输入中缀表达式: ";
cin>>ch;
for(i=0;i<maxbuffer;i++)
\{out[i]=ch[i];}
cout<<"请确认您输入的表达式: ";
while(out[j]!=‘#‘)
\{
cout<<out[j];
j++;
}
cout<<‘#‘<<endl;
display_out(s,out);
//caculate_array;
}
char display_out(char out_ch[32],char ch[])
\{
int top=-1;
int i=0,data[maxbuffer],n;
int j=0;
char sta[20];
while(ch[i]!=‘#‘)
\{
if(isalnum(ch[i]))
\{
while(isalnum(ch[i]))
\{
out_ch[j]=ch[i];
j++;
i++;
}out_ch[j]=‘ ‘;j++;
}
else\{
switch(ch[i])
\{
case ‘+‘:
case ‘-‘: if(sta[top]==‘(‘||top==-1)
\{
top++;
sta[top]=ch[i];
i++;
}
else
\{
//j--;
out_ch[j]=sta[top];
j++;
top--;
//i++;
}
break;
//break;
case ‘*‘:
case ‘/‘:if(sta[top]==‘*‘&&sta[top]==‘/‘)
\{
out_ch[j]=sta[top];
j++;
//i++;
top--;
}
else
\{
top++;
sta[top]=ch[i];
i++;
}
break ;
//break;
case ‘(‘:top++;
sta[top]=ch[i];
i++;
break;
case ‘)‘:if(sta[top]==‘(‘)
\{
top--;
i++;
}
if(top==-1)
\{
cout<<"错误: 第"<<j<<"个位置的“)”没有找到与之匹配的“(”";
ch[i]=‘#‘;j=0;
}
else
\{
//while(sta[top]!=‘(‘)\{
out_ch[j]=sta[top];
top--;
j++;
//}break;
}
break;
/*case ‘#‘: out_ch[j]=‘#‘;
j++;
break;*/
default:
cout<<" your input is error"<<endl;
ch[i]=‘#‘;
j=0;
break;
}
}
}while(top!=-1)
\{
out_ch[j]=sta[top];j++;
top--;
}
out_ch[j]=‘#‘;
n=0;
cout<<"逆波兰表达式为: ";
while(out_ch[n]!=‘#‘)
\{
cout<<out_ch[n];
n++;
}
cout<<endl;
j=0;
/*while(ch[j]!=‘#‘)
\{
top++;
data[top]=ch[j];
}
cout<<data[top];
*/
return out_ch[maxbuffer];
}
[此贴子已经被作者于2005-4-7 14:33:16编辑过]