【数据结构】栈的应用——括号匹配、逆波兰式

        关于栈的实现,这里就不再写啦,具体可以参考小编之前的文章哦。数组版、链表版都有https://blog.csdn.net/qq_47504614/article/details/119391837

https://blog.csdn.net/qq_47504614/article/details/119390211

栈解决括号匹配问题

算法步骤:
       
1:如果当前遍历到左括号,则入栈
        2:如果当前遍历到右括号,则出栈一个元素,看其是否与当前的右括号组成一对,如果不是,则匹配失败。或者在出栈过程中发生异常(从空栈中出栈),也匹配失败
        3:若能顺利遍历完成,检查栈中是否还有剩余元素,如果有,则匹配失败;如果没有,则匹配成功。

#include <iostream>
using namespace std;
#include "stack.h"
int main()
{
	Stack openings;
	char symbol;
	bool is_matched = true;
	while (is_matched && (symbol = cin.get()) != '\n')
	{
		if (symbol == '{' || symbol == '(' || symbol == '[')  //左括号入栈
			openings.push(symbol);
		//对于右括号,若栈为空,不能匹配;若栈不为空,访问栈顶元素 并将栈顶元素删除 
		else if (symbol == '}' || symbol == ')' || symbol == ']')
		{
			if (openings.empty())
			{
				cout << "unmatched closing bracked" << symbol
					<< "detected" << endl;
				is_matched = false;
			}
			else
			{
				char match;
				openings.top(match);
				openings.pop();
				//is_matched为括号匹配的情况
				is_matched = (symbol == '}' && match == '{') || (symbol == ')' && match == '(') ||
					(symbol == ']' && match == '[');
				
				if (!is_matched)
					cout << "Bad match" << match << symbol << endl;
			}
		}

	}
	//在循环完成之后,若栈不为空 输出有多余不匹配的括号
	if (!openings.empty())
		cout << "Unmatched opening bracket(s) detected." << endl;
}

逆波兰式

定义

       逆波兰式(Reverse Polish notation,RPN,或逆波兰记法),也叫后缀表达式(将运算符写在操作数之后)。

一个表达式E的后缀形式可以如下定义:

(1)如果E是一个变量或常量,则E的后缀式是E本身。

(2)如果E是E1 op E2形式的表达式,这里op是任何二元操作符,则E的后缀式为E1'E2' op,这里E1'和E2'分别为E1和E2的后缀式。

(3)如果E是(E1)形式的表达式,则E1的后缀式就是E的后缀式。

如:我们平时写a+b,这是中缀表达式,写成后缀表达式就是:ab+

(a+b)*c-(a+b)/e的后缀表达式为:(a+b)*c-(a+b)/e→((a+b)*c)((a+b)/e)- →((a+b)c*)((a+b)e/)- →(ab+c*)(ab+e/)- →ab+c*ab+e/-

计算方法

          新建一个表达式,如果当前字符为变量或者为数字,则压栈,如果是运算符,则将栈顶两个元素弹出作相应运算,结果再入栈,最后当表达式扫描完后,栈里的就是结果。

将一个普通的中缀表达式转换为逆波兰表达式的一般算法

       首先需要分配2个栈,一个作为临时存储运算符的栈S1(含一个结束符号),一个作为存放结果(逆波兰式)的栈S2(空栈),S1栈可先放入优先级最低的运算符#,注意,中缀式应以此最低优先级的运算符结束。可指定其他字符,不一定非#不可。从中缀式的左端开始取字符,逐序进行如下步骤:

(1)若取出的字符是操作数,则分析出完整的运算数,该操作数直接送入S2栈。

(2)若取出的字符是运算符,则将该运算符与S1栈栈顶元素比较,如果该运算符(不包括括号运算符)优先级高于S1栈栈顶运算符(包括左括号)优先级,则将该运算符进S1栈,否则,将S1栈的栈顶运算符弹出,送入S2栈中,直至S1栈栈顶运算符(包括左括号)低于(不包括等于)该运算符优先级时停止弹出运算符,最后将该运算符送入S1栈。

(3)若取出的字符是“(”,则直接送入S1栈顶。

(4)若取出的字符是“)”,则将距离S1栈栈顶最近的“(”之间的运算符,逐个出栈,依次送入S2栈,此时抛弃“(”。

(5)重复上面的1~4步,直至处理完所有的输入字符。

(6)若取出的字符是“#”,则将S1栈内所有运算符(不包括“#”),逐个出栈,依次送入S2栈。

完成以上步骤,S2栈便为逆波兰式输出结果。不过S2应做一下逆序处理。便可以按照逆波兰式的计算方法计算了!


#include <iostream>
using namespace std;
#include "stack.h"
char get_command()
{
	char command;
	bool waiting = true;
	cout << "Select command and press<Enter>:";
	//输入运算符,如果运算符合法 将waiting置为false 在下一把跳出循环;如果运算符不合法 提示用户重新输入
	while (waiting)
	{
		cin >> command;
		command = tolower(command);   //tolower将大写转换为小写,用户即可以输入Q 也可以输入q 更加便捷
		
		if (command == '?' || command == '=' || command == '+' ||command == '-' 
			|| command == '*' || command == '/' || command == 'q')
			waiting = false;
		else
		{
			cout << "Please enter a valid command:" << endl
				<< "[?]push to stack [=]print pop" << endl
				<< "[+] [-] [*] [/] are arithmetic operations" << endl
				<< "[Q]uit." << endl;

		}	
	}
	return command;
}
bool do_command(char command, Stack& numbers)
{
	double p, q;  //p为第一操作数、q为第二操作数
	switch (command)
	{
	case '?':
		cout << "Enter a real number:" << flush;
		cin >> p;
		if (numbers.push(p) == overflow)  //栈满
			cout << "Waring : Stack full,lost number" << endl;
		break;
	case '=':
		if (numbers.top(p) == underflow)  //栈为空
			cout << "Stack empty" << endl;
		else  //栈不为空,将栈顶元素输出
			cout << p << endl;
		break;
	//如果栈不为空,--count,此时count==1;在此基础上,如果栈中有两个元素,--count 此时count==0 再插入q+p的值
	case '+':
		if(numbers.top(p)==underflow)
			cout << "Stack empty" << endl;
		else
		{
			numbers.pop();
			if (numbers.top(q) == underflow)  //栈中不含第二操作数
			{
				cout << "Stack has just one entry" << endl;
				numbers.push(p);
			}
			else
			{
				numbers.pop();
				if(numbers.push(q+p)==overflow)
					cout<<" Waring : Stack full, lost result" << endl;
			}
		}
		break;
	case '-':
		if (numbers.top(p) == underflow)
			cout << "Stack empty" << endl;
		else
		{
			numbers.pop();
			if (numbers.top(q) == underflow)
			{
				cout << "Stack has just one entry" << endl;
				numbers.push(p);
			}
			else
			{
				numbers.pop();
				if (numbers.push(q - p) == overflow)
					cout << " Waring : Stack full, lost result" << endl;
			}
		}
		break;
	case '*':
		if (numbers.top(p) == underflow)
			cout << "Stack empty" << endl;
		else
		{
			numbers.pop();
			if (numbers.top(q) == underflow)
			{
				cout << "Stack has just one entry" << endl;
				numbers.push(p);
			}
			else
			{
				numbers.pop();
				if (numbers.push(q * p) == overflow)
					cout << " Waring : Stack full, lost result" << endl;
			}
		}
		break;
	/*case '/':
		break;*/
	case 'q':
		cout << "Calculation finished.\n";
		return false;

	}
	return true;
}
void introduction()
{
	cout << "Reverse Polish Calculator Program."
		<< "\n--------------------------------------" << endl;
}
void instructions()
{
	cout << "User commands are entered to read in and operate on double." << endl;
	cout << "The valid commands are as follows:" << endl
		<< "[Q]uit." << endl
		<< "[?] to enter an double onto a stack." << endl
		<< "[=] to print the top double in the stack" << endl
		<< "[+] [-] [*] [/] are arithmetic operations." << endl
		<< "These operations apply to the top pair of stacked doubles." << endl;

}
int main()
{
	Stack stored_numbers;
	introduction();
	instructions();
	while (do_command(get_command(), stored_numbers));
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

qq_47504614

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

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

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

打赏作者

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

抵扣说明:

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

余额充值