基於棧實現整數加法算法

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);

	}
}
 
發佈了48 篇原創文章 · 獲贊 1 · 訪問量 1780
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章