小言_互联网的博客

c++ class方式实现后缀表达式计算(数据结构)

393人阅读  评论(0)

1.介绍:

原理介绍https://blog.csdn.net/weixin_43386443/article/details/101615016

原理差不多,就是把结构体替换成class,和出栈进行了修改,采用出栈删除之前拿到数据并返回给调用方法。

2.源码展示:

#include <iostream>
#include <sstream>
using namespace std; 
/**
	@author: 
	@date  :
*/
class Stack{
	private:
		int data;				//数据
	public:
		Stack * next; 			//指向下一个类 
		
		void setData(int data){
			this->data = data;
		} 
		int getData(){
			return this->data;
		}
};

//4.出栈:删除最顶上的节点,并返回数据 
int pop(Stack * top){
	Stack * node;
	node = top->next;
	int val;
	if(top->next == NULL){
		return 0;
	}else{
		val = node->getData();
		top->next = node->next;
		delete(node);
		return val;
	}
	
} 

//3.展示栈
void show(Stack * top){
	Stack * p;	
	int idx = 0;
	p = top->next;
	do{
		idx ++;
		cout<<p->getData()<<endl;
		p = p->next; 
	}while(p != NULL);
	cout<<"length = "<<idx<<endl;
} 

//2.入栈 
void push(Stack * top,int num){
	Stack * p = new Stack;
	p->setData(num);
	p->next = top->next;
	top->next = p;
}

//5.开始计算
int count(Stack * top,char oper){
	int v1 = pop(top);
	int v2 = pop(top);
	int result = 0;
	switch(oper){
		case '+':result = v1 + v2;break;
		case '-':result = v1 - v2;break;
		case '*':result = v1 * v2;break;
		case '/':result = v1 / v2;break;
		default:cout<<"Invalid character!!"<<endl;break;
	}
	//得到结果之后把结果入栈
	push(top,result); 
	cout<<v1<<oper<<v2<<"="<<result<<endl; 
	return result;
} 

//1.输入
void input(Stack * top){
	string str;
	int idx = 0;
	int result = 0;
	string num = "";
	cout<<"input:";
	cin>>str;
	for(int i=0;i<str.size();i++){
		if(str[i] == '('){		//如果被括号包裹,就视为是一个整体数,比如(10) 
			//记录前括下标 和后扩下表,取中间的值
			idx++;
		}else if(str[i] == ')'){
			idx--;
			i++;			//下表增加跳过)
			//把值强转 
			int number;
			stringstream ss ;
			ss << num;
			ss >> number;
			push(top,number);
		}
		//如果idx不为0说明还在括号内
		if(idx != 0){
			//取里面的纯数字
			if(str[i] >= '0' && str[i] < '9'){
				num += str[i];				//拿到括号中的值 
			} 
		}else{
			if(str[i] >= '0' && str[i] < '9'){
				int val;
				stringstream ss ;
				ss << str[i];
				ss >> val;
				push(top,val);
			}else if(str[i] != ')' || str[i] != '('){
				result = count(top,str[i]);
			}
		}
	}
	
	cout<<"The calculated results are as follows:"<<result<<endl;
} 
 
int main(int argc, char** argv) {
	Stack * stack = new Stack;			//创建一个新节点 
	stack->next = NULL;
	input(stack);
//	show(stack);
	return 0;
}

3.备注:

转载请说明出处!!!


转载:https://blog.csdn.net/weixin_43386443/article/details/101636534
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场