首页 > 其他 > 详细

数据结构 表达式求值

时间:2015-08-05 22:28:15      阅读:327      评论:0      收藏:0      [点我收藏+]

实现表达式求值,以及表达式中括号是否匹配。

实现方法,建立两个栈,一个用来存放操作数,一个用来存放运算符。判断运算符优先级来确定什么时候出栈,利用一个数组去表示优先级

头文件代码如下:

#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED

#include <iostream>
#include <string.h>
using namespace std;


template<class Type>
class Stack
{
public:
	Stack(int sz = INIT_SIZE)
	{
		capacity = sz > INIT_SIZE ? sz: INIT_SIZE;
		base = new Type[capacity];
		top = 0;
	}

	~Stack()
	{
		destory();
	}
public:
	bool IsFull()
	{return top >= capacity;}

	bool IsEmpty()
	{return top == 0;}

	void push(const Type &x);
	void pop();
    int getSize() const;
	void show_Stack() const;
    bool getTop(Type& x);
    void clear();
    void destory();
private:
	enum{ INIT_SIZE = 8 };
	int capacity;
	Type *base;
	int top;
};

template<class Type>
void Stack<Type>::push(const Type &x)
{
    if (IsFull())
        return;
    base[top++] = x;
}

template<class Type>
void Stack<Type>::pop()
{
    if (IsEmpty())
        return;
    top--;
}

template<class Type>
int Stack<Type>::getSize() const
{
    cout<<"Size = "<<top<<endl;
    return top;
}

template<class Type>
void Stack<Type>::show_Stack() const
{
    int i = top-1;
    while (i >= 0)
        cout << base[i--]<<" ";
    cout<<endl;
}

template<class Type>
bool Stack<Type>::getTop(Type& x)
{
    if( IsEmpty() )
        return false;
    x = base[top-1];
    //cout<<"栈顶元素是: "<<x<<endl;
    return true;
}

template<class Type>
void Stack<Type>::clear()
{
    if (IsEmpty())
        return;
        while(top)
        {
            top--;
        }
}

template<class Type>
void Stack<Type>::destory()
{
    clear();
    delete base;
    base = NULL;
    top = 0;
    capacity = 0;
}

#endif // STACK_H_INCLUDED

主函数:

#include "Stack.h"

bool IsOper(char str);
char procede(char x,char y);
int operate (char x,char z,char y);

int EvaluateExpression(const char *str)
{
    Stack<char> OPTR;
    OPTR.push('#');
    char e,a;
    char result;
    int p,q,r;
    Stack<int>  OPND;
    OPTR.getTop(a);
    while( a != '#' || *str != '#')
    {
        if(!IsOper(*str))
        {
            OPND.push(*str);
            str++;
        }
        else
        {
            OPTR.getTop(e);
            switch( procede(e,*str) )
            {
                case '<':
                    OPTR.push(*str);str++;
                    break;
                case '=':
                    OPTR.pop();str++;
                    break;
                case '>':
                    OPTR.getTop(e);
                    char oper = e;
                    OPTR.pop();

                    OPND.getTop(p);
                    char b = p;
                    OPND.pop();

                    OPND.getTop(q);
                    char c = q;
                    OPND.pop();

                    result = operate(c,oper,b)+'0';
                    OPND.push(result);
                    break;
            }
        }

        OPTR.getTop(a);
    }
    return result;
}

int operate (char x,char z,char y)
{
    int m = x - '0';
    int n = y - '0';
    switch(z)
        {
            case '+':
                return m+n;
                break;
            case '-':
                return m-n;
                break;
            case '*':
                return m*n;
                break;
            case '/':
                return m/n;
                break;
        }
}

char procede(char x,char y)
{
    int i,j;
    int form[7][7] =
        {
            { 1, 1,-1,-1,-1,1, 1},
            { 1, 1,-1,-1,-1,1, 1},
            { 1, 1, 1, 1,-1,1, 1},
            { 1, 1, 1, 1,-1,1, 1},
            {-1,-1,-1,-1,-1,0, 1},
            { 1, 1, 1, 1, 2,1, 1},
            {-1,-1,-1,-1,-1,2,0}
        };
    switch(x)
        {
            case '+':
                i = 0;
                break;
            case '-':
                i = 1;
                break;
            case '*':
                i = 2;
                break;
            case '/':
                i = 3;
                break;
            case '(':
                i = 4;
                break;
            case ')':
                i = 5;
                break;
            case '#':
                i = 6;
                break;
        }
    switch(y)
        {
            case '+':
                j = 0;
                break;
            case '-':
                j = 1;
                break;
            case '*':
                j = 2;
                break;
            case '/':
                j = 3;
                break;
            case '(':
                j = 4;
                break;
            case ')':
                j = 5;
                break;
            case '#':
                j = 6;
                break;
        }
        if(form[i][j] == 1)
            return '>';
        else if(form[i][j] == -1)
            return '<';
        else
            return '=';
}

bool IsOper(char str)
{
    if( str >= 40 && str <= 47 || str == 35)
        return true;
    else
        return false;
}

bool Check(const char *str)
{
    Stack<char> st;
    char e;
    if(*str == ']' || *str == ')')         //   [([][])]
        return false;
    st.push(*str);
    while(*(str+1) != '\0')
    {
        if(*(str+1) == ']')
        {
            st.getTop(e);
            if(e == '[')
                st.pop();
            else
                return false;
        }
        else if(*(str+1) == ')')
        {
            st.getTop(e);
            if(e == '(')
                st.pop();
            else
                return false;
        }
        else
        {
            st.push(*(str+1));
        }
        str++;
    }
        if(st.IsEmpty())
            return true;
        else
            return false;
}

int main()
{
    //char *str = "[([][])]";
    int value = 0;
    char *str = "4+2*3-9/3#";
    value = EvaluateExpression(str);
    int a = value - '0';
    cout<<a<<endl;
    bool flag = Check(str);
    if(flag)
        cout<<"OK"<<endl;
    else
        cout<<"Error!"<<endl;
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

数据结构 表达式求值

原文:http://blog.csdn.net/zhongqi0808/article/details/47302529

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!