數據結構 棧 計算器
棧計算器的基本思想如下:
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;
}
運行截圖