顺序栈 中缀表达式转后缀表达式——计算器

可能会有人疑问读取栈中全部元素的条件是:

while(z1.base!=z1.top)//跳出说明栈空
{
    pop(z1,entry);
}

有疑问的是:z1.base=z1.top;时候还有一个z1.base没有读,其实实在pop();里面定义的,大家看一下:

void pop(tyust &s,type &e)
{
	if(s.top==s.base)cout<<"Empty!!";
	e=*(--s.top);
}

s.top指针先下移把base值读出给e;

/////////////////////////////////////////////////////////////////////////////////割///////////////////////////////////////////////////////////////////////////////////////////////////

贴计算器代码:

管理员输入常见算术表达式,先转换成逆波兰,计算机再计算,上一篇中介绍过顺序栈的初始化,直接贴main里的处理函数

/*
逆波兰表示
是符号则运算
是数字则入栈
输入以#结束
*/
/*
输入中缀表达式把数字直接入栈z1;
符号入栈z2;
z2出栈,组成完整的z1;

根据z1计算结果
*/
void main()
{
	type  entry=0,temp=0;//暂时temp
	type  t1,t2,t3;
	tyust s,z1,z2,z3;
	stack_init(s);
	stack_init(z1);
	stack_init(z2);
	stack_init(z3);
	/////////////////////////#结束//////////////////////////////
	while('#'!=entry)
	{
		cin>>entry;
		if(entry>='0'&&entry<='9')
		{
			push(z1,entry);//直接存放字符
		}else
		{
			if(entry==')')
			{
				//pop元素直到找到(
				while(entry!='(')
				{
					pop(z2,entry);
					if(entry!='(')
					push(z1,entry);//有可能复合运算//经测试可用
				}
			}
			else if(entry=='+'||entry=='-'||entry=='('||entry=='*'||entry=='/')//直接入栈z2
			{
				if((entry=='+'||entry=='-')&&(*(z2.top-1)=='*'||*(z2.top-1)=='/'))//如果后面优先级低于前面,则弹出
				{
					while(z2.base!=z2.top)
					{
						pop(z2,temp);
					    push(z1,temp);//此处全部出栈
					}
				}
				push(z2,entry);
			}

		}	

	}
	

	cout<<"我是观察者3:"<<*(z2.base)<<":::"<<*(z2.base+1)<<endl;

	while(z2.base!=z2.top)
	{
		pop(z2,entry);
		cout<<"观察者4:"<<entry<<endl;
		push(z1,entry);
	}
	cout<<"我是观察者1:"<<*(z1.top-2)<<":::"<<*(z1.top-1)<<endl;
	push(z1,'#');//结束符

	while(z1.base!=z1.top)
	{
		pop(z1,entry);
		
		push(z3,entry);
	}
	cout<<"我是观察者2:"<<*(z3.base+2)<<":::"<<*(z3.base+1)<<endl;
	//
	//////////////////////////割////////////////////////////////
	while('#'!=entry)
	{
		pop(z3,entry);
		if(entry>='0'&&entry<='9')//压入栈
		{
			entry-='0';
			push(s,entry);
		}else//判断是否是运算符
		{
			switch (entry)
			{
			case '+':
				pop(s,t1);
				pop(s,t2);
				push(s,t1+t2);
				break;
			case '-':
				pop(s,t1);
				pop(s,t2);
				push(s,t2-t1);
				break;
			case '*':
				pop(s,t1);
				pop(s,t2);
				push(s,t2*t1);
				break;
			case  '/':
				pop(s,t1);
				pop(s,t2);
				if(!t1)cout<<"ERROR"<<endl;
				else push(s,t2/t1);
				break;

			}
		}

	}
	pop(s,t3);
	cout<<"结果:"<<(int)t3<<endl;

}

效果如下,输入6/3+2*5+6+(2+3)*5#

猜你喜欢

转载自blog.csdn.net/shuiyihang0981/article/details/82316368