栈应用之计算全括号形式的数值表达式

本文探讨如何利用栈来判断一个全括号形式的中缀表达式是否正确配对,该表达式仅包含加减乘除二元运算符。

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

1.判断表达式括号是否配对

#include <iostream>
#include <stack>

using namespace std;

bool isBalanced(const string& expression) {
	const char left = '(', right = ')';
	bool flag = true;
	stack<char> chstack;
	char ch;
	for(int i = 0; i < expression.size(); i++) {
		ch = expression[i];
		if(ch == '(')
			chstack.push(ch);
		else if(ch == ')' && !chstack.empty())
			chstack.pop();
		else if(ch == ')' && chstack.empty()) {
			flag = false;
			break;
		}
	}
	return (chstack.empty() && flag);
}

2.计算数值表达式

使用条件:(1)表达式使用全括号形式,中缀表达式 (2)表达式中只能出现‘+’、‘-’、‘*’、‘/'等二元操作符,不能出现取反等一元操作符,即为非负数

#include <iostream>
#include <stack>
#include <cctype> 

using namespace std;

void evaluate_top(stack<double>& nums, stack<char>& operations) {
	double operd2 = nums.top();
	nums.pop();
	double operd1 = nums.top();
	nums.pop();
	switch(operations.top()) {
		case '+' : nums.push(operd1 + operd2);
					break;
		case '-' : nums.push(operd1 - operd2);
					break;
		case '*' : nums.push(operd1 * operd2);
					break;
		case '/' : nums.push(operd1 / operd2);
					break;
	}
	operations.pop();
}

double read_and_evaluate(istream &ins) {
	stack<char> chstack;
	stack<double> dstack;
	const char DECIMAL = '.', RIGHT_PAR = ')';
	double num;
	char ch;
	while(ins && ins.peek()!='\n') {
		if(isdigit(ins.peek()) || ins.peek() == DECIMAL) {
			ins >> num;
			dstack.push(num);
		}
		else if((ins.peek() == '+') || (ins.peek() == '-') || (ins.peek() == '*') || (ins.peek() == '/')) {
			ins >> ch;
			chstack.push(ch);
		}
		else if(ins.peek() == RIGHT_PAR) {
			ins.ignore();
			evaluate_top(dstack, chstack);	
		}
		else 
			ins.ignore();
	}
	return dstack.top();	
}

int main() {
	cout << "Type a fully parethesized arithmetic expression:" << endl;
	double result = read_and_evaluate(cin);
	cout << "That evaluates to " << result << endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值