数据结构实验四

堆栈的应用

一、 要求完成时间
实验开始后的第五周之前完成
二、 实验目的
掌握堆栈的使用。
三、 实验内容

  1. 输入一个数学表达式(假定表达式输入格式合法),计算表达式结果并输出。
  2. 数学表达式由单个数字和运算符“+”、“-”、“*”、“/”、“(、) ”构成,例如 2 + 3 * ( 4 + 5 ) - 6 / 4。
  3. 变量、输出采用整数,只舍不入。

四、注意事项
本题测试一定要多找几个测试用例,特别是复杂用例、边界用例。否则,很容易造成死机或者没有返回结果。

五、特别提醒:运行结果不稳定的原因
这个实验的程序容易出现运行结果不稳定情况,也容易出现死循环或者不正常退出的情况,
造成的原因大多是使用的非法内存,也就是数组变量越界引用,例如下面的引用就会造成非法引用。
int opStack[100];
Int I=0;
Int c;
…………如果你程序逻辑错误,运行到这个位置时c=101
opStack[c]=123; //这个时候opstack没有101数据,结果就操作了opstack数组后面的非法内存,
如果这个位置正好是程序,那就造成严重错误,如果是别的变量,比如是变量I的位置,那就造成i=123了,
这样的结果必然是错误的。

六、 测试用例及答案
测试如下用例,确保你的程序运行后出现完全一样的画面。
(操作系统提示“请按任意键继续。。。”等,可以不一样)。


#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<stack>
#include<algorithm>
using namespace std;
string str;
int que[10000], len = 0;
int prior[300];
stack<char>sta;
int calus(int a, int b, char s)
{
	return s == '+' ? a + b : s == '-' ? a - b : s == '*' ? a * b : a / b;
}
int main()
{
	cout << "Input" << endl;
	prior['+'] = 1;
	prior['-'] = 1;
	prior['*'] = 2;
	prior['/'] = 2;
	while (sta.size() > 0)sta.pop();

 	cin >> str;
		str = "(" + str + ")";
		for (int i = 0; i < str.length(); i++)
		{
			if (str[i] >= '0'&&str[i] <= '9')
			{
				int number = str[i] - '0';
				while (str[i + 1] >= '0'&&str[i + 1] <= '9') number = number * 10 + str[++i] - '0';

				que[len++] = number;
			}
			else
			{
				if (str[i] == '(') sta.push(str[i]);
				else if (str[i] == ')')
				{
					while (sta.top() != '(')
					{
						len--;
						que[len - 1] = calus(que[len - 1], que[len], sta.top());
						sta.pop();
					}
					sta.pop();
				}
				else
				{
					while (!sta.empty() && sta.top() != '('&&prior[sta.top()] >= prior[str[i]])
					{
						len--;
						que[len - 1] = calus(que[len - 1], que[len], sta.top());
						sta.pop();
					}
					sta.push(str[i]);
				}
			}
		}
		cout << "Output"<<endl;
		cout << que[--len] << endl;
		cout << "End" << endl;
//	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Chi Z犬里

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

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

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

打赏作者

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

抵扣说明:

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

余额充值