Infix expressions 中缀表达式

Posted KennyRom

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Infix expressions 中缀表达式相关的知识,希望对你有一定的参考价值。

中缀表达式的计算

利用两个栈来实现,操作数栈,操作符栈

只支持个位数运算

最后必须输入一个‘#‘

#include<iostream>
using namespace std;

template<typename ElementType>
struct Node
{
	ElementType data;
	Node<ElementType>* next;
};

template<typename ElementType>
class LinkStack
{
public:
	LinkStack()
	{
		top = new Node<ElementType>;
		top = NULL;
	}
	~LinkStack()
	{
		delete top;
	}
	void push(ElementType item);
	void pop();
	ElementType front() const;
private:
	Node<ElementType>*top;
};

template<typename ElementType>
void LinkStack<ElementType>::push(ElementType item)
{
	Node<ElementType>*p = new Node<ElementType>;
	p->data = item;
	p->next = top;
	top = p;
}

template<typename ElementType>
void LinkStack<ElementType>::pop()
{
	Node<ElementType>*p = top;
	top = top->next;
	delete p;
}

template<typename ElementType>
ElementType LinkStack<ElementType>::front()const
{
	return top->data;
}

bool isNum(char c)
{
	return (c <= ‘9‘ && c >= ‘0‘);
}

char Precede(char f, char c)
{
	if (f == ‘+‘)
	{
		if (c == ‘*‘ || c == ‘/‘ || c == ‘(‘)return ‘<‘;
		else return ‘>‘;
	}
	else if (f == ‘-‘)
	{
		if (c == ‘*‘ || c == ‘/‘ || c == ‘(‘)return ‘<‘;
		else return ‘>‘;
	}
	else if (f == ‘*‘)
	{
		if (c == ‘(‘)return ‘<‘;
		else return‘>‘;
	}
	else if (f == ‘/‘)
	{
		if (c == ‘(‘)return ‘<‘;
		else return‘>‘;
	}
	else if (f == ‘(‘)
	{
		if (c == ‘)‘)return ‘=‘;
		else return ‘<‘;
	}
	else if (f == ‘)‘)return ‘>‘;
	else if (f == ‘#‘)
	{
		if (c == ‘#‘)return ‘=‘;
		else return ‘<‘;
	}
}

int Operator(int a, int b, LinkStack<char>* L)
{
	if (L->front() == ‘+‘)
		return a + b;
	else if (L->front()== ‘-‘)
		return a - b;
	else if (L->front() == ‘*‘)
		return a*b;
	else if (L->front() == ‘/‘)
		return a / b;
}

void evaluate(LinkStack<char>*SOPTR, LinkStack<int>*SOPND)
{
	SOPTR->push(‘#‘);
	char c;
	cin >> c;
	while (c != ‘#‘ || SOPTR->front() != ‘#‘)
	{
		if (isNum(c))
		{
			int n = c - ‘0‘;
			SOPND->push(n);
			cin >> c;
		}
		else
		{
			switch (Precede(SOPTR->front(), c))
			{
			case ‘<‘:SOPTR->push(c);
				cin>>c;
				break;
			case ‘=‘:SOPTR->pop();
				cin >> c;
				break;
			case ‘>‘:
				int a = SOPND->front();
				SOPND->pop();
				int b = SOPND->front();
				SOPND->pop();
				SOPND->push(Operator(a, b, SOPTR));
				SOPTR->pop();
			}
		}
	}
	cout << SOPND->front() << endl;
	delete SOPND, SOPTR;
}

int main()
{
	cout << "input the infix expression:(you must input # to stop input)" << endl;
	LinkStack<char>* SOPTR = new LinkStack<char>;
	LinkStack<int>* SOPND = new LinkStack<int>;
	evaluate(SOPTR,SOPND);

	return 0;
}

以上是关于Infix expressions 中缀表达式的主要内容,如果未能解决你的问题,请参考以下文章

如何在Postfix和Infix表示法中接受负值?

中缀到前缀转换方案

书写表达式:中缀、后缀和前缀

栈的总结

在 SML Alice 中创建中缀/后缀/前缀解析器

程序改进与性能分析