四则运算包括括号一般用栈来实现。
#include "stack.h"
#include <string>
#include <iostream>
using namespace std;

int main(int argc,char *argv[])
{
    //char *a = argv[1];
   // char *a = "(((2*(3-3))+5)*3)";
    char *a = "4*3-2";
    size_t len = strlen(a);

    //the operation value
    MyStack<int> opv(128);
    //the opeartion transfer
    MyStack<char> opt(128);


    for(int i=0;i<len;i++)
    {
        if((a[i]>='0')&&(a[i]<='9'))
                //cout<<a[i];
        {
            opv.push(0);
   
        }
        while((a[i]>='0')&&(a[i]<='9'))
        opv.push(opv.pop()*10+a[i++]-'0');
        if(')'== a[i])
        {
            char c = opt.pop();
            if('*' == c)
            opv.push(opv.pop()*opv.pop());
            if('+' == c)
            opv.push(opv.pop()+opv.pop());
            if('-' == c)
            opv.push(-(opv.pop()-opv.pop()));
        }


   
        if(('-'== a[i])||('+' == a[i])||('*' == a[i]))
        {
            opt.push(a[i]);
        }
    }
    cout<<opv.pop()<<endl;


}
Posted on 2008-07-22 15:40 micheal's tech 阅读(1024) 评论(0)  编辑 收藏 引用 所属分类: Algorithm

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理