后缀评估算法
postfix evaluation algorithm
这是我对评估后缀评估的尝试
#include<iostream>
#include<string>
using namespace std;
template<class T>
class Stack
{
private:
T *s;int N;
public:
Stack(int maxn)
{
s=new T[maxn];
N=0;
}
int empty()const
{
return N==0;
}
void push(T k)
{
s[N++]=k;
}
T pop()
{
return s[--N];
}
};
int main()
{
//postfix evaluation
char *a="3+4*5";
int N=strlen(a);
Stack<int>save(N);
for(int i=0;i<N;i++)
{
if(a[i]=='+')
save.push(save.pop()+save.pop());
if(a[i]=='*')
save.push(save.pop()*save.pop());
if((a[i]>='0' && a[i]<='9'))
save.push(0);
while((a[i]>='0' && a[i]<='9'))
save.push(10*save.pop()+(a[i++]-'0'));
}
cout<<save.pop()<<" "<<endl;
return 0;
}
但是,它给出的不是答案23,因为4*5+3=23,而是答案5,正如我所理解的,这段代码给我这个结果是因为,首先它检查i=0是否有+标记,这不是,然后它检查如果是*,这也不是,所以它首先推0,然后它计算10*0+'3'-'0',这等于3,(它将在堆栈中推),对于i=1,a[i]等于3,所以它打印3+,第二个pop是未定义的,所以我认为这是错误的,请帮助我修复
这需要一个小的修复:
#include <iostream>
#include <cstring>
using namespace std;
template<class T>
class Stack
{
private:
T *s;
int N;
public:
Stack(int maxn)
{
s = new T[maxn];
N = 0;
}
int empty()const
{
return N == 0;
}
void push(T k)
{
s[N++] = k;
}
T pop()
{
return s[--N];
}
};
int main()
{
//postfix evaluation
const char *a = "3 4 5*+";
int N = strlen(a);
Stack<int>save(N);
for (int i = 0; i < N; i++)
{
if (a[i]=='+')
save.push(save.pop() + save.pop());
if (a[i]=='*')
save.push(save.pop() * save.pop());
if (a[i] >= '0' && a[i] <= '9')
{
save.push(0);
while (a[i] >= '0' && a[i] <= '9')
save.push(10 * save.pop() + a[i++] - '0');
i--;
}
}
cout << save.pop() << " " << endl;
return 0;
}
输出(视频):
23
现在,如果删除我添加的i--;
,代码将跳过a[]
中的字符,因为i
在a[i++]
和for (int i = 0; i < N; i++)
中有两个增量。
如果没有i--;
,输出为(视频):
9
相关文章:
- std::condition_variable::wait()如何评估给定的谓词
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 基于ELO的团队匹配算法
- C++选择排序算法中的逻辑错误
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- C++A*算法并不总是在路径中具有目标节点
- 排序算法c++
- 构建可组合有向图(扫描仪生成器的汤普森构造算法)
- 算法问题:查找从堆栈中弹出的所有序列
- 下面是排序算法O(n)吗
- KMP算法和LPS表构造的运行时间
- c++11评估顺序(未定义的行为)
- 为什么我的排序算法会更改数组值
- 求最大元素位置的分治算法
- 具有非整数边容量的最大流量的Dinic算法
- 到连接组件算法的问题(递归)
- STL算法函数在多个一维容器上的使用
- 读取最后一行代码算法 - c++ 时出现问题
- 括号更改 O(n) 算法
- 后缀评估算法