C++栈的应用之表达式求值
作者:网络转载 发布时间:[ 2015/11/25 13:32:48 ] 推荐标签:测试开发技术 .NET
Stack.hpp
#pragma once
template <class T>
class Stack{
private:
T* _array;
size_t _capacity;
int _topindex;
public:
Stack() //构造函数
:_array(0)
, _capacity(0)
, _topindex(-1)
{}
void Push(const T& x){ //入栈操作
if (_topindex + 1 == _capacity){
_capacity = 2 * _capacity + 3;
T* tmp = new T[_capacity];
if (tmp == NULL){
cout << "failed new" << endl;
exit(-1);
}
memcpy(tmp, _array, sizeof(T) * (_topindex + 1));
delete _array;
_array = tmp;
}
_array[++_topindex] = x;
}
void Pop(){ //出栈
if (_topindex > -1){
//cout << _array[_topindex] << endl;
_topindex--;
}
}
bool empty(){ //清空
return _topindex = -1;
}
const T& top(){ //取栈顶元素
//cout << _array[_topindex] << endl;
return _array[_topindex];
}
};
main.cpp
#include<iostream>
#include<string>
#include"Stack.hpp"
using namespace std;
enum Type{
ADD,
SUB,
MUL,
DIV,
OP_NUM,
};
struct Cell{
Type _type;
int num;
};
Cell RPNExp[] = {
OP_NUM, 12,
OP_NUM, 3,
OP_NUM, 4,
ADD, 1,
MUL, 1,
OP_NUM, 6,
SUB, 1,
OP_NUM, 8,
OP_NUM, 2,
DIV, 1,
ADD, 1,
};
int main(){
Stack<int> s2;
int i = 0;
for (int i = 0; i < sizeof(RPNExp) / sizeof(RPNExp[0]);i++){ //取出元素
int left, right; //两个操作数
switch (RPNExp[i]._type){ //将栈中数据出栈
case ADD: //如果是加号,取两个操作数
left = s2.top();
s2.Pop();
right = s2.top();
s2.Pop();
s2.Push(left + right); //新的值入栈
break;
case SUB: //如果是减号,取两个操作数
left = s2.top();
s2.Pop();
right = s2.top();
s2.Pop();
s2.Push(right - left);
break;
case MUL: //如果是乘号,取两个操作数
left = s2.top();
s2.Pop();
right = s2.top();
s2.Pop();
s2.Push(left * right);
break;
case DIV: //如果是除号,取两个操作数
left = s2.top();
s2.Pop();
right = s2.top();
s2.Pop();
s2.Push(right / left);
break;
case OP_NUM: //如果数字,入栈
s2.Push(RPNExp[i].num);
break;
default:
return -1;
}
}
cout << s2.top() << endl;
return 0;
}
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11