实验内容及要求:
从键盘输入后缀表达式(运算符和 *** 作数建议以字符串形式输入,空格作为分隔符),计算并输出后缀表达式的求值结果。
基本要求:实现 +, -, *, /四个二元运算符;
实现+, -两个一元运算符(即正、负号);
*** 作数用整数表示。
提高要求:输出对应的前缀表达式。
每位同学可必须实现基本要求,可选择实现提高要求;程序可不处理表达式语法错误。
实验目的:掌握堆栈在表达式求值中的应用。
#define _CRT_SECURE_NO_WARNINGS 1
#include
#include
#include
#include
using namespace std;
//节点结构体
typedef struct Node
{
int data;
struct Node* next;
}SNode;
//定义栈结构OPND来储存 *** 作数和运算结果
typedef struct Stack {
SNode* top;
int stackSize;
}OPND;
//初始化栈
bool InitStack(OPND * & S) {
S->top = NULL;
if (S->top != NULL)
return false;
S->stackSize = 0;
return true;
}
//压栈
bool Push(OPND * & S, int e) {
SNode* newNode = new Node;
newNode->data = e;
newNode->next = S->top;
S->top = newNode;
S->stackSize++;
return true;
}
bool Pop(OPND* & S,int &e) {
if (S->stackSize == 0)
return false;
SNode* p = S->top;
e = p->data;
S->top = p->next;
delete p;
S->stackSize--;
return true;
}
int Operate(int a1, int a2, char op)
{
switch (op)
{
case '+':
return a1 + a2;
break;
case '-':
return a1 - a2;
break;
case '*':
return a1 * a2;
break;
case '/':
return a1 / a2;
break;
}
}
int GeTResult(OPND* & S)
{
if (S->stackSize==0)
return 0;
return S->top->data;
}
int main() {
string arr;
OPND * d1 = new OPND;
InitStack(d1);
cout << "从键盘输入后缀表达式(运算符和操作数建议以字符串形式输入,空格作为分隔符)"
<< endl;
getline(cin, arr);
istringstream ss(arr);
vector words;
string word;
while (ss >> word) {
words.push_back(word);
}
for (string x : words) {
if (x == "-" ||x == "+" || x=="*" || x =="/") {
const char* p = x.c_str();
int a1 = 0, a2 = 0;
Pop(d1, a1);
Pop(d1, a2);
//将两个 *** 作数取出来之后进行相应的运算。
int result = Operate(a2, a1, p[0]);
Push(d1, result);
}
else {
//将字符串类型转化为int型
stringstream geek(x);
int p;
geek>>p;
Push(d1, p);
}
}
cout << "表达式计算的结果是:" << GeTResult(d1) << endl;
return 0;
}
输入:6 5 2 3 + 8 * + 3 + *
运行结果
本人实力有限,做法有些复杂,还望大哥们不吝赐教!!!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)