Q1:假设一个算术表达式中包含圆括弧、方括弧和花括弧三种类型的括弧,编写一个判别表达式中括弧是否正确配对的函数 correct(exp,tag);其中,exp 为字符串类型的变量,表示被判别的表达式,tag 为布尔型变量。
使用栈st进行判断,将"(","["或"{"入栈,当遇到")","]"或"}"时,检查当前栈顶元素是否是对应的"(","["或"{"若是则退栈,否则返回表示不配对.
当栈为空时,表示整个表达式检查完毕.括号正确配对.
CODE:
// correct.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define Maxsize 100 //Maxsize为算术表达式中最多字符个数
int correct(char exp[]){
char st[Maxsize];
int top=0,i=0;
int tag=1;
while(exp[i]!='/0' && tag){
if(exp[i]=='(' || exp[i]=='[' || exp[i]=='{'){//遇到'(','[','{',则将其入栈
top++;
st[top]=exp[i];
}
if(exp[i]==')'){//遇到')',若栈顶是'(',则继续,否则不配对返回
if(st[top]=='(') top--;
else tag=0;
}
if(exp[i]==']'){//遇到']',若栈顶是'[',则继续,否则不配对返回
if(st[top]=='[') top--;
else tag=0;
}
if(exp[i]=='}'){//遇到'}',若栈顶是'{',则继续,否则不配对返回
if(st[top]=='{') top--;
else tag=0;
}
i++;
}
if(top>0)tag=0;//若栈不空,则不配对
return tag;
}
void main(){
int tag;
char exp[] = "{1+2)*[(3+6)*9]}";
printf("表达式为:%s/n",exp);
tag = correct(exp);
if(tag==0)
printf("表达式括弧不配对/n");
else
printf("表达式括弧配对/n");
}
RUN:
Q2:编写一个函数求逆波兰表达式的值,其中波兰表达式是在该函数中输入的。
使用一个数栈stack,逆波兰表达式存放在字符型数组exp中,依次扫描逆波兰表达式,
当遇到运算对象时,就把它压入数栈stack;
当遇到运算符时,就执行两次弹出熟栈stack中的数进行运算,再把结果压入栈;
重复,直到扫描到终止符"#",在栈顶得到表达式的值.
My View:根据前天的转逆波兰式的方法改进函数.一般表达式->逆波兰表达式->求表达式的值.
CODE:
#include "stdafx.h"
#define Maxsize 100/*Maxsize为算术表达式中最多字符个数*/
char str[Maxsize];//存储原算术表达式
char exp[Maxsize];//存储转换后的波兰表达式
void trans()
{
char stack[Maxsize];//作为栈使用
char ch;
int i,j,t,top=0;//t作为exp下标,top作为stack下标,i作为str下标
i=0;//获取用户输入的表达式
do
{
i++;
scanf("%c",&str[i]);
}while((str[i]!='#')&&(i<Maxsize));
t=0;i=0;
ch=str[i];i++;
while(ch!='#')
{
if((ch>='0')&&(ch<='9'))//判定为数字
{
exp[t]=ch;t++;
}else
if(ch=='(')//判定为左括号
{
top++;
stack[top]=ch;
}else
if(ch==')')//判定为右括号
{
while(stack[top]!='(')
{
exp[t]=stack[top];
top--;
t++;
}
top--;//将左括号弹出
}else
if((ch=='+')||(ch=='-'))//判定为加减号
{
while((top!=0) && (stack[top]!='('))
{
exp[t]=stack[top];
top--;
t++;
}
top++;
stack[top]=ch;
}else
if((ch=='*')||(ch=='/'))//判定为乘除
{
while((stack[top]=='*')||(stack[top]=='/'))
{
exp[t]=stack[top];
top--;
t++;
}
top++;
stack[top]=ch;
}
ch=str[i];//继续判断字符
i++;
}
while(top!=0)
{
exp[t]=stack[top];
t++;
top--;
}
exp[t]='#';
exp[t+1]='/0';
printf("逆波兰表达式为:");
for(j=0;j<=t;j++)
printf("%c",exp[j]);
printf("/n");
}
void compvalue()
{
//char expCopy[Maxsize];//存储转换后的波兰表达式
float stack[Maxsize];//作为栈使用
char c;
int i=0,t=0,top=0;//t作为exp下标,top作为stack下标,i作为str下标
/*do//获取逆波兰表达式
{
i++;
expCopy[i]=exp[i];
}
while((exp[i]!='#') && (i<Maxsize));*/
c=exp[t];
t++;
while(c!='#')
{
if((c>='0') && (c<='9'))//判定为数字字符
{
float d=c-'0';//将数字字符转换为对应的数值
top++;
stack[top]=d;
}
else//判定为运算符
{
switch(c)
{
case'+':
stack[top-1]=stack[top-1]+stack[top];break;
case'-':
stack[top-1]=stack[top-1]-stack[top];break;
case'*':
stack[top-1]=stack[top-1]*stack[top];break;
case'/':
if(stack[top]!=0)
stack[top-1]=stack[top-1]/stack[top];
else printf("除零错误!/n");
break;
}
top--;
}
c=exp[t];
t++;
}
printf("计算结果是:%g/n",stack[top]);
}
void main()
{
trans();
compvalue();
}
RUN:
哈哈,闪………………