Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ private void manageMultiAndDivOper(String[] elements,Stack numStack,Stack operSt
preElement = (Float)numStack.pop();
i++;
nextElement = Float.valueOf(elements[i]);
numStack.push(doBaseOper(preElement,nextElement,elements[i-1]));
numStack.push(Token.doBaseOper(preElement,nextElement,elements[i-1]));
}
}
}
Expand All @@ -42,27 +42,12 @@ private void manageMultiAndDivOper(String[] elements,Stack numStack,Stack operSt
private float manageAddAndMinusOper(Stack numStack,Stack operStack){
float result = 0f;;
while(!operStack.isEmpty()){
result = doBaseOper(result,(Float)numStack.pop(),(String)operStack.pop());
result = Token.doBaseOper(result,(Float)numStack.pop(),(String)operStack.pop());
}
result += (Float)numStack.pop();
return result;
}

private float doBaseOper(float preData,float nextData,String oper){
switch(oper){
case "+":
return preData+nextData;
case "-":
return preData-nextData;
case "*":
return preData*nextData;
case "/":
return preData/nextData;
default:
throw new RuntimeException("could not recognise oper:"+oper);
}
}

public String[] getElementArray(String expression){
char[] charArray = expression.toCharArray();
StringBuffer stringBuffer = new StringBuffer();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.github.ipk2015.coding2017.basic.stack.expr;



import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;

public class InfixToPostfix {

public static List<Token> convert(String expr) {
int len = expr.length();
char c,temp;
Stack stack = new Stack();
StringBuffer buffer = new StringBuffer();
for(int i = 0;i<len;i++){
c = expr.charAt(i);
if(Character.isDigit(c)){
buffer.append(c); //数字字符直接放进buffer里
}else{
buffer.append(" ");
if('(' == c){
stack.push(c); // ( 时先放进字符栈里
}else if(')' == c){ // ) 时将栈里到上一个(之间的字符全部压出到buffer里
temp = (Character)stack.pop();
while(temp!='('){
buffer.append(temp);
temp = (Character)stack.pop();
};
}else{ //四个运算符时,
while(!shouldPush(c,stack)){
buffer.append((Character)stack.pop());
}
stack.push(c);
}
}
}
while(!stack.isEmpty()){
buffer.append((Character)stack.pop());
}
TokenParser parser = new TokenParser();
return parser.parse(buffer.toString());
}
/*
* 比较该运算符与临时栈栈顶指针的运算符的优先级,如果临时栈栈顶指针的优先级大于等于该运算符的优先级,
* 弹出并添加到后缀表达式中,反复执行前面的比较工作,直到遇到一个栈顶指针的优先级低于该运算符的优先级,
* 停止弹出添加并把该运算符压入栈中。
* 此时的比较过程如果出现栈顶的指针为‘(’,则停止循环并把该运算符压入栈中
*
*/
private static boolean shouldPush(char c,Stack stack){
if(stack.isEmpty()){
return true;
}
char peek = (Character)stack.peek();
if(peek == '('){
return true;
}
if((c == '*' || c == '/') && (peek == '+' || peek == '-')){
return true;
}
return false;
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package com.github.ipk2015.coding2017.basic.stack.expr;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

public class InfixToPostfixTest {

@Before
public void setUp() throws Exception {
}

@Test
public void testConvert() {
List<Token> tokens = InfixToPostfix.convert("3+(2-5)*6/3");

Assert.assertEquals(3, tokens.get(0).getIntValue());
Assert.assertEquals(2, tokens.get(1).getIntValue());
Assert.assertEquals(5, tokens.get(2).getIntValue());
Assert.assertEquals("-", tokens.get(3).toString());
Assert.assertEquals(6, tokens.get(4).getIntValue());
Assert.assertEquals("*", tokens.get(5).toString());
Assert.assertEquals(3, tokens.get(6).getIntValue());
Assert.assertEquals("/", tokens.get(7).toString());
Assert.assertEquals("+", tokens.get(8).toString());
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.github.ipk2015.coding2017.basic.stack.expr;

import java.util.List;
import java.util.Stack;

public class PostfixExpr {
String expr = null;

public PostfixExpr(String expr) {
this.expr = expr;
}

public float evaluate() {
TokenParser parser = new TokenParser();
List<Token> list = parser.parse(expr);

Stack stack = new Stack();
int len = list.size();
float preNum,afterNum;
Token token;
for(int i = 0;i<len;i++){
token = list.get(i);
if(token.isNumber()){
stack.push(Float.valueOf(token.toString()));
}else{
afterNum = (Float)stack.pop();
preNum = (Float)stack.pop();
stack.push(Token.doBaseOper(preNum, afterNum, token.toString()));
}
}
return (Float)stack.pop();
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.github.ipk2015.coding2017.basic.stack.expr;



import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;



public class PostfixExprTest {

@Before
public void setUp() throws Exception {
}

@After
public void tearDown() throws Exception {
}

@Test
public void testEvaluate() {
{
PostfixExpr expr = new PostfixExpr("6 5 2 3 + 8 * + 3 + *");
Assert.assertEquals(288, expr.evaluate(),0.0f);
}
{
//9+(3-1)*3+10/2
PostfixExpr expr = new PostfixExpr("9 3 1-3*+ 10 2/+");
Assert.assertEquals(20, expr.evaluate(),0.0f);
}

{
//10-2*3+50
PostfixExpr expr = new PostfixExpr("10 2 3 * - 50 +");
Assert.assertEquals(54, expr.evaluate(),0.0f);
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.github.ipk2015.coding2017.basic.stack.expr;

import java.util.Iterator;
import java.util.List;
import java.util.Stack;

public class PrefixExpr {
String expr = null;

public PrefixExpr(String expr) {
this.expr = expr;
}

public float evaluate() {
TokenParser parser = new TokenParser();
List<Token> list = parser.parse(expr);

Stack stack = new Stack();
int len = list.size();
float preNum,afterNum;
Token token;
for(int i = 0;i<len;i++){
token = list.get(len-i-1);
if(token.isNumber()){
stack.push(Float.valueOf(token.toString()));
}else{
preNum = (Float)stack.pop();
afterNum = (Float)stack.pop();
stack.push(Token.doBaseOper(preNum, afterNum, token.toString()));
}
}
return (Float)stack.pop();
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package com.github.ipk2015.coding2017.basic.stack.expr;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;


public class PrefixExprTest {

@Before
public void setUp() throws Exception {
}

@After
public void tearDown() throws Exception {
}

@Test
public void testEvaluate() {
{
// 2*3+4*5
PrefixExpr expr = new PrefixExpr("+ * 2 3* 4 5");
Assert.assertEquals(26, expr.evaluate(),0.001f);
}
{
// 4*2 + 6+9*2/3 -8
PrefixExpr expr = new PrefixExpr("-++6/*2 9 3 * 4 2 8");
Assert.assertEquals(12, expr.evaluate(),0.001f);
}
{
//(3+4)*5-6
PrefixExpr expr = new PrefixExpr("- * + 3 4 5 6");
Assert.assertEquals(29, expr.evaluate(),0.001f);
}
{
//1+((2+3)*4)-5
PrefixExpr expr = new PrefixExpr("- + 1 * + 2 3 4 5");
Assert.assertEquals(16, expr.evaluate(),0.001f);
}


}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package com.github.ipk2015.coding2017.basic.stack.expr;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Token {
public static final List<String> OPERATORS = Arrays.asList("+", "-", "*", "/");
private static final Map<String,Integer> priorities = new HashMap<>();
static {
priorities.put("+", 1);
priorities.put("-", 1);
priorities.put("*", 2);
priorities.put("/", 2);
}
static final int OPERATOR = 1;
static final int NUMBER = 2;
String value;
int type;
public Token(int type, String value){
this.type = type;
this.value = value;
}

public boolean isNumber() {
return type == NUMBER;
}

public boolean isOperator() {
return type == OPERATOR;
}

public int getIntValue() {
return Integer.valueOf(value).intValue();
}
public String toString(){
return value;
}

public boolean hasHigherPriority(Token t){
if(!this.isOperator() && !t.isOperator()){
throw new RuntimeException("numbers can't compare priority");
}
return priorities.get(this.value) - priorities.get(t.value) > 0;
}

public static float doBaseOper(float preData,float nextData,String oper){
switch(oper){
case "+":
return preData+nextData;
case "-":
return preData-nextData;
case "*":
return preData*nextData;
case "/":
return preData/nextData;
default:
throw new RuntimeException("could not recognise oper:"+oper);
}
}


}
Loading