基于栈实现整数加法算法

package com.hongjindong.Stack;

public class calculate {

	private int MaxSize = 20;
	int[] AStack = new int[MaxSize];
	int top = -1;

	public void push(int Value) {//入栈

		if (top >= MaxSize) {
			System.out.println("The stack is full! ");

		} else {

			top++;
			AStack[top] = Value;

		}
	}

	public int pop() {//出栈
		int temp;

		if (top < 0) {
			System.out.println("The stack is empty!");
			return -1;
		}

		temp = AStack[top];
		top--;
		return temp;
	}

	public boolean IsOperator(int operator) {//判断是否是运算符

		if (operator == 43 || operator == 45 || operator == 42
				|| operator == 47)
			return true;
		else
			return false;

	}

	public int Priority(int operator) {//判断优先级
		if (operator == 43 || operator == 45)
			return 1;
		else if (operator == 42 || operator == 47)
			return 2;
		else
			return 0;
	}

	public int TwoResult(int operator, int operand1, int operand2) {//两个数的运算

		switch (operator) {
		case 43:
			return (operand2 + operand1);
		case 45:
			return (operand2 - operand1);
		case 42:
			return (operand2 * operand1);
		case 47:
			return (operand2 / operand1);//注意这里写表达式的顺序
		}
		return 0;
	}

	public static void main(String[] args) {

		calculate Operator = new calculate();
		calculate Operand = new calculate();
		String Expression = "8*9-2*4";
		int Position = 0;
		int Operator1;
		int Operand1 = 0;
		int Operand2 = 0;
		int Result = 0;

		while (true) {

			if (Operator.IsOperator((int) Expression.charAt(Position))) {//判断读入的是否是运算符

				if (Operator.top != -1) {//如果运算符栈还有符号,判断两者的优先级
					if (Operator.Priority((int) Expression.charAt(Position)) <= Operator
							.Priority(Operator.AStack[Operator.top])) {//栈类的运算符优先级大,先计算
						Operand1 = Operand.pop();
						Operand2 = Operand.pop();
						Operator1 = Operator.pop();

						Operand.push(Operand.TwoResult(Operator1, Operand1,
								Operand2));
					}
				}
				Operator.push((int) Expression.charAt(Position));//运算符进栈
			}

			else {
				Operand.push((int) Expression.charAt(Position) - 48);//整数进栈

			}

			Position++;
			if (Position >= Expression.length())
				break;
		}

		while (Operator.top != -1) {//出栈

			Operand1 = Operand.pop();
			Operand2 = Operand.pop();
			Operator1 = Operator.pop();

			Operand.push(Operand.TwoResult(Operator1, Operand1, Operand2));
		}
		Result = Operand.pop();
		System.out.println("The expression result is :" + Result);

	}
}
 

你可能感兴趣的:(算法)