33,311
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
using namespace std;
#include"stack.h"
#include<stdlib.h>
int MAXNUM = 65535;
const int opsize = 5;
class compute :public stack
{
public:
int count(char *); //中缀表达式计算过程
int getopindex(char); //取得某一运算符在运算符数组中的下标
private:
static char op[opsize]; //运算符数组
static int prior[opsize][opsize]; //优先数组
};
char compute::op[opsize] = { '+','-','*','/','#' };
int compute::prior[opsize][opsize] =
{ { 2,2,1,1,2 },
{ 2,2,1,1,2 },
{ 2,2,2,2,2 },
{ 2,2,2,2,2 },
{ 1,1,1,1,3 } };
int compute::getopindex(char c)
{
int flag = -1;
for (int i = 0; i<opsize; i++)
if (c == op[i])
{
flag = i;
break;
return flag;
}
}
int compute::count(char *exp)
{
stack opnd, optr;
char op, num1, num2;
optr.push('#');
for (char *p = exp ; *p != '\0';)
{
if (*p >= '0'&&*p <= '9')
{
opnd.push(*p); p++;
}
else if (getopindex(*p) != -1)
{
if (prior[getopindex(optr.gettop())][getopindex(*p)] == 1)
{
optr.push(*p);
p++;
}
else if (prior[getopindex(optr.gettop())][getopindex(*p)] == 2)
{
optr.pop(&op);
opnd.pop(&num2);
opnd.pop(&num1);
if (op == '+') opnd.push(num1 + num2 - '0');
else if (op == '-') opnd.push(num1 - num2 + '0');
else if (op == '*') opnd.push((num1 - '0')*(num2 - '0') + '0');
else if (op == '/') opnd.push((num1 - '0') / (num2 - '0') + '0');
}
else if (prior[getopindex(optr.gettop())][getopindex(*p)] == 3)
{
return opnd.gettop() - '0';
}
}
else return MAXNUM;
}
}
int main()
{
char *ex= new char;
cout << "请输入一个以#开头和结尾的表达式";
cin >> ex;
compute c;
int res = c.count(ex);
cout << "\n结果是:"<< res << endl;
system("pause");
return 0;
}
char stack::gettop() //取栈顶元素
{
if(top=base) //括号内的表达式应该是判断表达式而非赋值表达式
return '\0';
else return *(top-1);
}
int compute::getopindex(char c)
{
int flag = -1;
for (int i = 0; i<opsize; i++)
if (c == op[i])
{
flag = i;
break;
//return flag; //此句放在这儿没有意义,因为执行break之后return flag就不会再执行。
}
}
class stack //栈类
{
public:
stack();
~stack();
void clearstack(); //清空
int isempty(); //判空
int length(); //求长度
char gettop(); //取栈顶元素
int push(char); //进栈
int pop(char*); //出栈
void traverse(); //遍历
protected:
char *base; //栈顶指针
char *top; //栈底指针
};
stack.cpp
#include <iostream>
using namespace std;
#include "stack.h"
const int stacksize=10;
stack::stack()
{
top=base=new char[stacksize];
}
stack::~stack()
{
delete[] base;
}
void stack::clearstack() //清空
{
top=base;
}
int stack::isempty() //判空
{
if(top==base)
return 1;
else return 0;
}
int stack::length() //求长度
{
int i;
char *p;
for(i=0,p=top;p!=base;)
{
p--;
i++;
}
return i;
}
char stack::gettop() //取栈顶元素
{
if(top=base)
return '\0';
else return *(top-1);
}
int stack::push(char c) //进栈
{
if(top-base==stacksize)
return 0;
else {
*top=c;
top++;
return 1;
}
}
int stack::pop(char *p) //出栈
{
if(top==base)
return 0;
else{
top--;
*p=*top;
return 1;
}
}
void stack::traverse() //遍历
{
for(char *p=top-1;p>base;p--)
cout<<*p<<"->";
cout<<*p<<endl;
}