[英]multiplying polynomials using linked list in java
這是我使用喜歡的列表將兩個多項式相乘的代碼。它可以正常工作,但問題是我是否將(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轉換回列表。
我希望我不會為您解決一些學校作業或運動。 在這種情況下,您不應該使用它!
此解決方案不使用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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.