这是我使用喜欢的列表乘以两个多项式的代码。它工作正常,但问题是如果我乘以 (3x^2+5x+3)*(4x^3+5^x+2)
我得到的结果为 12x^5+15x^2+6x^2+20x^4+25x^2+10x+12x^3+15x +6。
但是我怎样才能使它输出具有相似指数的项相加在一起,例如 12x^5+43x^2+..
public class LinkedPoly{
static String exponent="";
Node2 head;
Node2 current;
LinkedPoly(){
head=null;
}
public void createList(int c,int e){
head=new Node2(c,e,head);
}
public static LinkedPoly multiply(LinkedPoly list1,LinkedPoly list2){
Node2 temp1=list1.head;
Node2 temp2=list2.head;
Node2 temp3=temp2;
LinkedPoly multiplyList=new LinkedPoly();
while(temp1!=null){
while(temp2!=null){
multiplyList.createList((temp1.coef*temp2.coef),(temp1.exp+temp2.exp));
temp2=temp2.next;
}
temp2=temp3;
temp1=temp1.next;
}
return multiplyList;
}
最佳答案
一个想法是将这些值放入一个以指数次数为键的映射中,并用一个指示系数的值。即,
Map<Integer,Integer> exponents = new HashMap<Integer,Integer>()
....
// inside your while loop
int newcoeff = temp1.coef*temp2.coef
int newexp = temp1.exp+temp2.exp
if(exponents.containsKey(newexp))
exponents.put(newexp, exponents.get(newexp) + newcoeff)
else
exponents.put(newexp,newcoeff)
然后将 HashMap 转换回列表。
关于java - 在java中使用链表乘多项式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24415540/