public class Test5 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Node n1=new Node();
Node n2=new Node();
Node n3=new Node();
Node n4=new Node();
Node n5=new Node();
Node n6=new Node();
n1.exp=3;n1.cof=2;n1.next=n2;
n2.exp=1;n2.cof=1;n2.next=n3;
n3.exp=0;n3.cof=3;n3.next=null;
n4.exp=2;n4.cof=2;n4.next=n5;
n5.exp=1;n5.cof=9;n5.next=n6;
n6.exp=0;n6.cof=30;n6.next=null;
Node nPlus=plus(n1,n4);
print(nPlus);
//print(n1);
}
public static Node plus(Node n1,Node n2){
if(n1==null && n2==null)
return null;
if(n1==null)
return n2;
if(n2==null)
return n1;
Node tmpNode1=n1;
Node tmpNode2=n2;
Node tmpNode3=new Node();
Node n3=tmpNode3;
while(tmpNode1!=null && tmpNode2!=null){
if(tmpNode1.exp>tmpNode2.exp){
tmpNode3.next=tmpNode1;
tmpNode1=tmpNode1.next;
tmpNode3=tmpNode3.next;
System.out.println("111111111111");
}
else if(tmpNode1.exp<tmpNode2.exp){
tmpNode3.next=tmpNode2;
tmpNode2=tmpNode2.next;
tmpNode3=tmpNode3.next;
System.out.println("22222222222");
}
else{
if(tmpNode1.cof+tmpNode2.cof!=0){
Node tmpNode4=new Node(); //必须在这里new一个新对象,否则每次赋值会覆盖前一个值
tmpNode4.cof=tmpNode1.cof+tmpNode2.cof;
tmpNode4.exp=tmpNode1.exp;
tmpNode3.next=tmpNode4;
tmpNode3=tmpNode3.next;
System.out.println(tmpNode3.cof+".."+tmpNode3.exp);
System.out.println("3333333333333");
}
tmpNode1=tmpNode1.next;
tmpNode2=tmpNode2.next;
}
}
if(tmpNode1!=null){
tmpNode3.next=tmpNode1;
System.out.println("444444444444");
}
if(tmpNode2!=null){
tmpNode3.next=tmpNode2;
System.out.println("55555555");
}
tmpNode3.next=null;
return n3;
}
public static void print(Node n){
while(n.next!=null){
n=n.next;
System.out.print(n.cof+"*X^"+n.exp);
if(n.next!=null)
System.out.print("+");
}
System.out.println();
}
}
class Node{
int cof;
int exp;
Node next;
}