C++用栈Stack实现数学复合运算

          关键思想是运算符的优先级设置,分别使用一个数字栈和一个运算符栈,等到运算符栈为空,运算结束了。

  compute.cpp

// compute.cpp : Defines the entry point for the console application.
//

#include
using namespace std;
#include"StdAfx.h"
#include"Stack.h"
//先实现一个3+4#
//判断符号优先级
char Priority(char ch1,char ch2);
//传入出栈的2个数字和一个运算符并且计算该二元运算。比如3+5、8*9
int Compute(int a,int b,char sign);

int main(){
	Stack number;//数字栈
    Stack character;//运算符栈
	character.Push('#');
	int ch = getchar();
    //它从标准输入里读取下一个字符。返回类型为int型,返回值为用户输入的ASCⅡ码,出错返回-1,比如输入a ,返回97,输入3,返回51
	char b;
	b=static_cast(ch);//b是ch转换的字符
	while(b!='#' || character.getTop()!='#'){
		if(ch>48 && ch<=57){//这里非常容易写错啊!不是ch>0 && ch<=9,或者b>0 && b<=9;
			number.Push(ch-48);
			ch = getchar();
			b=static_cast(ch);
		}
		else{
			switch( Priority( character.getTop(),  b)){
			case'<'://栈顶元素优先级低
				character.Push(b);
				ch = getchar();
				b=static_cast(ch);
				break;
			case'='://脱一个'('括号 并且接收下一个字符
				character.Pop();
				ch = getchar();
				b=static_cast(ch);
				break;
			case'>'://出栈并且把运算结果入栈
				number.Push(Compute(number.Pop(),number.Pop(),character.Pop()));
				/*int result=number.Pop()+number.Pop();
				cout<';
}
//传入出栈的2个数字和一个运算符并且计算该二元运算。比如3+5、8*9
int Compute(int a,int b,char sign){
	int result;
	switch(sign){
		case '+'  : 	result=a+b;
			break;
		case '-'  : 	result=a-b;
			break;
		case '*'  : 	result=a*b;
			break;
		case '/'  : 	result=a/b;
			break;
		case '%'  : 	result=a%b;
			break;
		case '^'  : 	result=a^b;
			break;
	}
	return result;
}
/**

*/

 

Stack.h

//...................................................................................节点类
#ifndef STACK_H
#define STACK_H
template
class Node{
    public:
	T element;
	Node *next;
	//构造函数
	Node(T element){
		this->element = element;
		next = NULL;
	}
};
//..................................................................................栈类
template
class Stack{
private:
	Node *top;
	int size;
public:
	//构造函数
    Stack(){
		//头结点赋值为0;
		Node *newNode = new Node(0);
		top = newNode;
		size = 0;//无需因为头结点把size 初始化为1;
	}
	//返回栈的长度
	int stackLength(){
		return size;
	}
	//判栈为空
    bool stackEmpty(){
		if(0==size)
			return true;
		else
			return false;
	}
	//入栈
    void Push(T e){
		Node *newNode = new Node(e);
		newNode->next = top->next;
		top->next = newNode;
		size++;
	}
	//出栈
    T Pop(){
		Node *current = top->next;
		top->next = current->next;
		T f=current->element;
		delete current;
		size--;
		return f;
	}
	//返回栈顶元素
	T getTop(){
		return top->next->element;
	}
};
#endif  

 

 

你可能感兴趣的:(数据结构;栈)