java中使用链表的多项式乘法
这是我使用liked list将两个多项式相乘的代码。它工作得很好,但问题是如果我相乘(3x^2+5x+3)*(4x^3+5^x+2) 我得到的结果是12x^5+15x^2+6x^2+20x^4+25x^2+10x+12x^3+15x +六, 但是我怎样才能使它输出具有类似指数的项加在一起,比如12x^5+43x^2+java中使用链表的多项式乘法,java,data-structures,linked-list,polynomials,Java,Data Structures,Linked List,Polynomials,这是我使用liked list将两个多项式相乘的代码。它工作得很好,但问题是如果我相乘(3x^2+5x+3)*(4x^3+5^x+2) 我得到的结果是12x^5+15x^2+6x^2+20x^4+25x^2+10x+12x^3+15x +六, 但是我怎样才能使它输出具有类似指数的项加在一起,比如12x^5+43x^2+ public class LinkedPoly{ static String exponent=""; Node2 head; Node2 current
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)
Map exponents=newhashmap()
....
//在你的while循环中
int newcoeff=temp1.coef*temp2.coef
int newexp=temp1.exp+temp2.exp
if(指数containsKey(newexp))
指数.put(newexp,指数.get(newexp)+newcoeff)
其他的
指数put(newexp,newcoeff)
然后将HashMap转换回列表。我希望我没有为你解决一些学校作业或练习。那样的话,你不应该用它 此解决方案不使用
Map
,但它比@dfb发布的解决方案慢得多
/**
* @param list will be modified (merged).
* @return the merged list param.
*/
public static LinkedPoly merge(LinkedPoly list) {
Node2 temp1 = list.head;
while (temp1 != null) {
Node2 iter = temp1;
Node2 temp2 = iter.next;
while (temp2 != null) {
if (temp1.exp == temp2.exp) {
temp1.coef += temp2.coef;
//removing temp2 form the source list
iter.next = temp2.next;
}
iter = iter.next;
temp2 = iter.next;
}
temp1 = temp1.next;
}
return list;
}
与其调用
LinkedPoly.multiply(a,b)
只需调用LinkedPoly.merge(LinkedPoly.multiply(a,b))
这是正确的基本思想。为了避免调用containsKey
和调用get
,最好只调用get
,然后检查结果是否为空。@DavidWallace-在这种情况下,这无关紧要,但对于允许空值的映射结构来说,这通常不是一个好的实践,因为您无法区分项目是否缺失null@dfb:谢谢你的回答。但我还没有学会地图。因此,如果你能用另一种方法指导我,那将非常有用: