上个星期的作业,现在才改好。。。。。
基本思路:
当我们从键盘上输入一串字符,比如1+(2+3),建立两个栈,一个存放运算符的栈toperator,一个存放操作数number,依次遍历。
遇到操作数就依次存放到操作栈里;
遇到运算符时,优先级高的就直接压进运算符栈里,优先级低的就依次弹出操作栈中的两个值与运算符进行计算,然后把计算的值再次压进操作数栈里。其中有括号的情况,左括号的直接压进,当右括号遇到左括号的时候就直接弹出左括号。
程序:
类模块:
#ifndef _STACK_H_
#define _STACK_H_
#include<iostream>
using namespace std;
template<typename T>
class Stack
{
public:
Stack(int maxSIZE);
~Stack();
void Push(const T& n);
void Pop();
T& getTop() const;
bool Empty() const;
private:
T *s_;
int top_;
int maxSIZE_;
};
template <typename T>
Stack<T>::Stack(int maxSIZE):maxSIZE_(maxSIZE),top_(-1)
{
s_ = new T[maxSIZE];
}
template<typename T>
Stack<T>::~Stack()
{
delete []s_;
}
template<typename T>
void Stack<T>::Push(const T& n)
{
if(top_ == maxSIZE_-1)
{
throw(1);
}
top_++;
s_[top_] = n;
}
template<typename T>
void Stack<T>::Pop()
{
if(Empty() == true)
{
throw(1);
}
top_--;
}
template<typename T>
T& Stack<T>::getTop() const
{
if(Empty() == true)
{
throw(1);
}
return s_[top_];
}
template<typename T>
bool Stack<T>::Empty()const
{
return top_+1 == 0;
}
#endif
#include<iostream>
#include"stack.h"
#include<cstdlib>
#include<cstring>
using namespace std;
Stack<int> number(100);
Stack<char> toperator(100);
int calsum(int a,int b,char ope)//计算过程
{
if(ope == '*')
{
b = b*a;
}
if(ope == '/')
{
b = b/a;
}
if(ope == '+')
{
b = b+a;
}
if(ope == '-')
{
b = b-a;
}
return b;
}
int priority(char ch)//优先级
{
if(ch == '(' || ch == ')')
{
return -1;
}
if(ch == '+' || ch == '-')
{
return 0;
}
if(ch == '*' || ch == '/')
{
return 1;
}
}
int is_number(char ch)//判断是数字还是运算符
{
if(ch >= '0' && ch <= '9')
{
return 1;
}
return 0;
}
int calculate(char* buffer)
{
int i = 0;
int a;
int b;
int sum;
while(buffer[i] != '\0')
{
if((is_number(buffer[i])) == 1)//是字符数字
{
int num = buffer[i] - '0';//将字符转换为数字
number.Push(num);//将操作数压栈
}
if((is_number(buffer[i])) == 0)//是运算符
{
if((toperator.Empty()) == 1)
{
toperator.Push(buffer[i]);//首次压栈
}
else//不是第一次压栈
{
if((priority(buffer[i]))>(priority(toperator.getTop())) || buffer[i] == '(')//优先级高的入栈
{
toperator.Push(buffer[i]);
}
else
{
a = number.getTop();
number.Pop();
b = number.getTop();
number.Pop();
b = calsum(a,b,toperator.getTop());
number.Push(b);
toperator.Pop();
if(toperator.getTop() == '(' && buffer[i] == ')')
{
toperator.Pop();//当两个括号相遇的时候,删除左括号
}
}
}
}
i++;//往后依次遍历
}
while(toperator.Empty() != true)//遍历结束,但是栈中还有数
{
a = number.getTop();
number.Pop();
b = number.getTop();
number.Pop();
b = calsum(a,b,toperator.getTop());
number.Push(b);
toperator.Pop();
}
return b;
}
int main()
{
char buffer[100];
int sum;
cout<<"please input a string:\n"<<endl;
cin>>buffer;
try
{
sum = calculate(buffer);
printf("the sum is %d\n",sum);
}
catch(int a)
{
cout<<"number failed"<<__LINE__<<endl;
}
catch(char ch)
{
cout<<"operator failed"<<__LINE__<<endl;
}
}