您的位置:首页 > 其它

用栈实现 表达式求值的运算源码

2010-09-10 11:27 295 查看
说明:表达式以#结尾

// Evaluate.cpp : Defines the entry point for the console application.

//

#include "stdafx.h"

#define STACK_SIZE 100

#define BIG 1

#define SMALL -1

#define EQUAL 0

//#define TRUE 1

//using namespace std;

class Stack

{

public:

Stack();

~Stack();

void iniStack();

void desStack();

void push(int a);

bool isEmpty();

int getTop();

int pop();

//getElem();

private:

int *data;

int top;

int length;

};

Stack::Stack()

{

top = -1;

length = 0;

data = NULL;

}

Stack::~Stack()

{

}

void Stack::iniStack()

{

data = new int[STACK_SIZE];

}

void Stack::desStack()

{

delete [] data;

data = NULL;

}

void Stack::push(int a)

{

top++;

data[top] = a;

}

int Stack::pop()

{

return data[top--];

}

bool Stack::isEmpty()

{

return top == -1;

}

int Stack::getTop()

{

return data[top];

}

int precede(char a,char b)

{

int r = 0;

switch (a)

{

case '+':

if (b == '+' || b == '-' || b == ')' || b == '#')

r = BIG;

else if(b == '*' || b == '/' || b == '(' )

r = SMALL;

break;

case '-':

if (b == '+' || b == '-' || b == ')' || b == '#')

r = BIG;

else if(b == '*' || b == '/' || b == '(')

r = SMALL;

break;

case '*':

if ( b == '(' )

r = SMALL;

else if(b == '+' || b == '-' || b == '*' || b == '/' || b == ')'|| b == '#')

r = BIG;

break;

case '/':

if ( b == '(' )

r = SMALL;

else if(b == '+' || b == '-' || b == '*' || b == '/' || b == ')'|| b == '#')

r = BIG;

break;

case '(':

if(b == '+' || b == '-' || b == '*' || b == '/' || b == '(')

r = SMALL;

else if(b == ')')

r = EQUAL;

break;

case ')':

r = BIG;

case '#':

if(b == '#')

r = EQUAL;

else

r = SMALL;

break;

}

return r;

}

bool isOpertor(char a)

{

return (a=='+' || a=='-' || a=='*' || a=='/' || a=='(' || a==')' || a=='#');

}

int jisuan(int a,int b,char opertor)

{

switch (opertor)

{

case '+':

return a + b;

break;

case '-':

return a - b;

break;

case '*':

return a * b;

break;

case '/':

return a / b;

break;

}

}

int main(int argc, char* argv[])

{

Stack oper,opnd;

oper.iniStack();

oper.push('#');

opnd.iniStack();

char instr[100] = {0};

scanf("%s",instr);

//printf("%s/n" , instr);

int i=0;

int j=0;

char temp;

char t1[100] = {0};

while (instr[i] != NULL)

{

if(!isOpertor(instr[i]))//如果不是操作符号

t1[j++] = instr[i];

//opnd.push(instr[i]-48);

else

{

j=0;

int a = atoi(t1);

memset(t1,0,100);

opnd.push(a);

while (precede(oper.getTop(),instr[i]) == BIG )//如果之前进栈的运算符优先级更高,则先运算之前的

{

opnd.push(jisuan(opnd.pop(),opnd.pop(),oper.pop()));

}

if( precede(oper.getTop(),instr[i]) == SMALL )

{

oper.push(instr[i]);

}

else if( precede(oper.getTop(),instr[i]) == EQUAL)

oper.pop();

}

i++;

}

printf("%d/n",opnd.pop());

oper.desStack();

opnd.desStack();

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: