数据结构 栈 计算器
栈计算器的基本思想如下:
1.用两个栈分别用于保存运算符和操作数(也可能是局部的计算结果),可以分别称之为操作数栈和运算符栈。
2.依次扫描表达式中的基本符号(操作数的运算符均看作一个基本符号)。扫描到了操作数则压入操作数栈,运算符压入运算符栈。
a. 如果扫描到的运算符优先级低于运算符栈顶的运算符,则运算符入栈,不发生运算。
b. 如果扫描到的运算符优先级高于栈顶的运算符,则取出栈顶的运算符,接着取出操作数栈的两个操作数进行运算,并将结果入到操作数的栈中。
#include<iostream>
#include<string>
using namespace std;
enum status { FLASE, TRUE };
template<class T>
class stack
{
public:
stack();
~stack();
status empty();
status push(T x);
status pop();
T get_top();
private:
struct node
{
T data;
node *next;
};
int count;
node *top;
};
template<class T>
stack<T>::stack()
{
count = 0;
top = NULL;
}
template<class T>
stack<T>::~stack()
{
while (!empty()) pop();
}
template<class T>
status stack<T>::empty()
{
if (count == 0) return TRUE;
else return FLASE;
}
template<class T>
status stack<T>::push(T x)
{
node *pnew=new node;
pnew->data = x;
pnew->next = top;
top = pnew;
count++;
return TRUE;
}
template<class T>
status stack<T>::pop()
{
if (empty()) cout << "已空" << endl;
node *pdelete;
pdelete = top;
top = pdelete->next;
delete pdelete;
count--;
return TRUE;
}
template<class T>
T stack<T>::get_top()
{
if (empty()) cout << "栈为空" << endl;
return top->data;
}
int symbol(char c) //赋予优先级
{
switch (c)
{
case '#': return 0;
case '+': return 2;
case '-': return 2;
case '*': return 3;
case '/': return 3;
case '(': return 4;
case ')': return 1;
default: break;
}
return 0;
}
int jisuan(int &a, int &b, char &c)
{
switch (c)
{
case '+': return b + a;
case '-': return b - a;
case '*': return b * a;
case '/': return b / a;
default: break;
}
return 0;
}
void main()
{
stack<int>s1;
stack<char>s2;
string a;
cout << "请输入" << endl;
cin >> a;
a = a + '#';
s2.push('#');
for (int i = 0; a[i] != 0; i++)
{
if (a[i] <= 47) //用阿斯克码判断扫描到的是数字还是运算符
{
if (a[i] == '#'&&s2.get_top() == '#') break; //两个#碰到一起运算结束
if (s2.get_top() == '(') //括号特殊讨论
{
if (a[i] == ')')
{
s2.pop();
continue;
}
s2.push(a[i]);
continue;
}
else if (symbol(s2.get_top()) >= symbol(a[i])) //判断运算符优先级
{
char temp1 = s2.get_top();
s2.pop();
int temp2 = s1.get_top();
s1.pop();
int temp3 = s1.get_top();
s1.pop();
s1.push(jisuan(temp2, temp3, temp1));
i--;
continue;
}
else
{
s2.push(a[i]);
continue;
}
}
else //对数字的运算
{
int sum = static_cast<int>(a[i]) - 48;
for (; a[i + 1] > 47; i++) //实现多位数的运算
sum = sum * 10 + static_cast<int>(a[i + 1]) - 48;
s1.push(sum);
continue;
}
}
int result = s1.get_top();
cout << "计算结果:" << endl;
cout << result << endl;
}
运行截图