头文件CHAR.H
#pragma once
#include<iostream>
#define OK 1
#define ERROR 0
using namespace std;
class CHAR
{
private:
typedef struct StackNode
{
char data;
struct StackNode *next;
}*Stack;
public:
Stack S = NULL;
CHAR()
{
InitStack();
}
int InitStack()//初始化
{
S = NULL;
return OK;
}
int Push(char e)//入栈
{
Stack p = new StackNode;
p->data = e;
p->next = S;
S = p;
return OK;
}
char Pop()//出栈
{
if (S == NULL) return ERROR;
int e = S->data;
Stack p = S;
S = S->next;
delete p;
return e;
}
char GetTop()//获得栈顶元素
{
if (S == NULL) return ERROR;
return S->data;
}
int StackEmpty()
{
if (S == NULL)
{
return 0;
}
else
{
return 1;
}
}
};
LINKSTACK.H
#pragma once
#include<iostream>
#define OK 1
#define ERROR 0
using namespace std;
class LinkStack
{
private :
typedef struct StackNode
{
int data;
struct StackNode *next;
}*Stack;
public :
Stack S = NULL;
LinkStack()
{
InitStack();
}
int InitStack()//初始化
{
S = NULL;
return OK;
}
int Push(int e)//入栈
{
Stack p = new StackNode;
p->data = e;
p->next = S;
S = p;
return OK;
}
int Pop()//出栈
{
if (S == NULL) return ERROR;
int e = S->data;
Stack p = S;
S = S->next;
delete p;
return e;
}
int GetTop()//获得栈顶元素
{
if (S == NULL) return ERROR;
return S->data;
}
int StackEmpty()
{
if (S == NULL)
{
return 0;
}
else
{
return 1;
}
}
};
#include"LinkStack.h"
#include"CHAR.h"
#include<iostream>
using namespace std;
int In(char ch)//判断是否为数字
{
if (ch >= '0' && ch <= '9')
{
return 1;
}
return 0;
}
char Precede(char a, char b)
{
char c;
if (a == '#' && b != '#') c = '<';
if (a == '#' && b == '#') c = '=';
else if ( a == '+' || a == '-')
{
if (b == '+' || b == '-' || b == ')' || b == '#')
{
c = '>';
}
else
{
c = '<';
}
}
else if (a == '*' || a == '/')
{
if (b == '(')
{
c = '<';
}
else
{
c = '>';
}
}
else if (a == '(')
{
if (b == ')')
{
c = '=';
}
else if (b == '+' || b == '-' || b == '*' || b == '/' || b == '(')
{
c = '<';
}
}
else if (a == ')')
{
if (b == '+' || b == '-' || b == '*' || b == '/' || b == ')')
{
c = '>';
}
}
return c;
}
int Operate(int a, char b, int c)//运算函数
{
int sum = 0;
switch (b)
{
case '+':
sum = a + c;
break;
case '-':
sum = a - c;
break;
case '*':
sum = a * c;
break;
case '/':
sum = a / c;
break;
default:
break;
}
return sum;
return 0;
}
int main()
{
LinkStack OPND;
CHAR OPTR;
int num = 0;
OPTR.Push('#');
char theta;//运算符
int a, b;//运算数
char ch;//输入
cin >> ch;
while (ch != '#' || OPTR.GetTop() != '#')
{
if (In(ch))
{
num = ((ch - '0') + num * 10);
cin >> ch;
}
else
{
if (num != 0)
{
OPND.Push(num);
num = 0;
}
switch (Precede(OPTR.GetTop(), ch))
{
case '<':
OPTR.Push(ch);
cin >> ch;
break;
case '>':
theta = OPTR.Pop();
b = OPND.Pop();
a = OPND.Pop();
OPND.Push(Operate(a, theta, b));
break;
case '=':
OPTR.Pop();
cin >> ch;
break;
}
}
}
cout << OPND.GetTop();
return 0;
}