直接代码
package work;
public class Fun {
public boolean isOperator(char c){
if('+'==c||'-'==c||'*'==c||'/'==c||'^'==c||'%'==c){
return true;
}else
return false;
}
public boolean isOpenParenthesis(char c){
return '('==c;
}
public boolean isCloseParenthesis(char c){
return ')'==c;
}
public int priority(char c){
if(c=='^')return 3;
if('*'==c||'/'==c||'%'==c)return 2;
else if ('+'==c||'-'==c)return 1;
else return 0;
}
public String converToPostfix(String expression)throws Exception{
LinkList st = new LinkList();
String postfix = new String();
for(int i = 0;i<expression.length()||expression!=null;i++){
char c = expression.charAt(i);
System.out.println(postfix);
if(' '!=c){
if(isOpenParenthesis(c)){
st.insert(c);
}
else if(isCloseParenthesis(c)){
char ac = (Character)st.pop();
while(!isOpenParenthesis(c)){
postfix = postfix.concat(String.valueOf(ac));
ac = (Character)st.pop();
}
}
else if(isOperator(c)){
if(!st.isEmpty()){
char ac = (Character)st.pop();
while(ac != 0 && priority(ac)>=priority(c)){
postfix = postfix.concat(String.valueOf(ac));
ac = (Character)st.pop();
}
if(ac != 0){
st.insert(ac);
}
}
st.insert(c);
}
else{
postfix = postfix.concat(String.valueOf(c));
}
}
}
while(st.isEmpty())
postfix = postfix.concat(String.valueOf(st.pop()));
return postfix;
}
}
package work;
public class LinkList {
public Node head ;
public void insert(Object date){
Node p = new Node(date);
p.next = head;
head = p;
}
public Object pop(){
if(isEmpty())
return null;
else{
Node p = head;
head = head.next;
return p.date;
}
}
public boolean isEmpty() {
// TODO Auto-generated method stub
return head==null;
}
}
package work;
public class Node {
public Object date;
public Node next;
//��
public Node(){
this.next = null;
}
//�в�
public Node(Object date){
this();
this.date = date;
}
}
package work;
public class Example {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Fun f = new Fun();
String postfix = f.converToPostfix("1+2+3");
System.out.println(postfix);
}
}
Exception in thread "main" java.lang.NullPointerException
at work.Fun.converToPostfix(Fun.java:48)
at work.Example.main(Example.java:8)
抛出这样的错误
_