(栈的应用5.2.2)POJ 2106 Boolean Expressions(表达式求值)

本文介绍了一个用于解析逻辑表达式的C++程序,该程序能够处理包含逻辑运算符“&”、“|”和“!”的表达式,并通过栈来实现正确的运算顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 * POJ_2106.cpp
 *
 *  Created on: 2013年10月30日
 *      Author: Administrator
 */

#include <iostream>
#include <cstdio>

using namespace std;

const int maxn = 110;

int op[maxn], otop;
int val[maxn],vtop;

void insert(int b){//将操作数b压入操作数栈val
	while(otop && op[otop - 1] == 3){//在压入之前对b进行!运算
		b = !b;
		--otop;
	}

	val[vtop++] = b;
}

void calc(){//进行双目运算
	int b = val[--vtop];
	int a = val[--vtop];
	int opr = op[--otop];

	int c = (a&b);//默认进行&运算
	if(opr == 1){//如果运算符为|
		c = a|b;
	}

	insert(c);
}


int main(){
	char c;

	int counter = 1;
	while((c = getchar()) != EOF){//要理解并记住这种形式的输入输出处理
		otop = 0;
		vtop = 0;

		do{
			if( c == '('){
				op[otop++] = 0;
			}else if(c == ')'){//处理)内的所有运算,结果压入val栈
				while(otop && op[otop - 1] != 0){//只要没有遇到匹配的(,就继续进行运算
					calc();
				}
				--otop;
				insert(val[--vtop]);
			}else if(c == '!'){
				op[otop++] = 3;
			}else if(c == '&'){
				while(otop && op[otop - 1] >= 2){//将op栈中所有优先级比&的运算符出栈进行运算
					calc();
				}

				op[otop++] = 2;//将&压入op栈
			}else if(c == '|'){
				while(otop && op[otop - 1] >= 1){
					calc();
				}

				op[otop++] = 1;
			}else if(c == 'V' || c == 'F'){
				insert(c == 'V'?1:0);
			}
		}while((c = getchar()) != '\n' && c != EOF);

		while(otop){//将op栈中的所有元素出栈进行运算
			calc();
		}

		printf("Expression %d: ",counter++);
		printf(val[0]?"V":"F");
		printf("\n");
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

帅气的东哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值