模拟栈实现逆波兰表达式

​ 用C++模拟栈来实现逆波兰表达式求解算式~

/*************************************************************************
	> File Name: p.cpp
	> Author: Zcy
	> Mail: 296763002@qq.com
	> Created Time: 三  1/23 18:16:17 2019
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
using namespace std;

template <typename type> class S{
private:
	type *val;
	int head;
public:
	void push(type val) {
		this -> head ++;
		this -> val[this -> head] = val;
	}
	void pop() {
		this -> head --;
	}
	bool empty() {
		return this -> head < 0;
	}
	type top() {
		return this -> val[this -> head];
	}
	bool bj(char c) {
		if ((c == '+' || c == '-') && (top() == '*' || top() == '/')) {
			return true;
		} else if ((c == '+' || c == '-') && (top() == '+' || top() == '-')){
			return true;
		} else if ((c == '*' || c == '/') && (top() == '*' || top() == '/')){
			return true;
		} else {
			return false;
		}
	}
	void init() {
		this -> val = (type *)malloc(sizeof(type) * 25);
		this -> head = -1;
	}
	void clear() {
		free(this -> val);
		free(this);
	}
};

int jsx(char c, int a, int b) {
	switch(c) {
		case '*':
			return a * b;
			break;
		case '/':
			return a / b;
			break;
		case '+':
			return a + b;
			break;
		default:
			return a - b;
	}
}

void js(S<int> *num, S<char> *ch) {
	int b = num -> top();
	num -> pop();
	int a = num -> top();
	num -> pop();
	num -> push(jsx(ch -> top(), a, b));
	ch -> pop();
}

int main () {
	char *buffer = (char *)malloc(sizeof(char) * 25);
	scanf("%s", buffer);
	int val = 0;
	S<int> *num = (S<int> *)malloc(sizeof(S <int>));
	S<char> *ch = (S<char> *)malloc(sizeof(S <char>));
	num -> init();
	ch -> init();
	for (int i = 0; buffer[i]; i++) {
		if (isdigit(buffer[i])) {
			val = val * 10 + buffer[i] - '0';
		} else {
			num -> push(val);
			val = 0;
			while(!ch -> empty() && ch -> bj(buffer[i])) {
				js(num, ch);
			}
			ch -> push(buffer[i]);
		}
	}
	num -> push(val);
	while(!ch -> empty()) {
		js(num, ch);
	}
	printf("%d\n", num -> top());
	free(buffer);
	num -> clear();
	ch -> clear();
	return 0;
}

转载请注明出处!!!

如果有写的不对或者不全面的地方 可通过主页的联系方式进行指正,谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值