2014-06-25 29 views
0

這是我使用喜歡列表乘以兩個多項式的代碼。它工作正常,但問題是如果我乘以(3x^2 + 5x + 3)*(4x^3 + 5^x +2)在java中使用鏈接列表乘以多項式

我得到結果爲12x^5 + 15x^2 + 6x^2 + 20x^4 + 25x^2 + 10x + 12x^3 + 15x +6。

但我怎麼可以把它與同類指數是togther增加等,使得它輸出方面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; 
    } 
+0

相關:http://stackoverflow.com/questions/24394860 – dedek

回答

1

一個想法是把值到地圖用指示係數的值鍵入指數的程度。即,

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轉換回列表。

+0

這是一個正確的基本理念。爲了避免調用'containsKey'並調用'get',最好調用'get',然後檢查結果是否爲空。 –

+0

@DavidWallace - 在這種情況下它並不重要,但對於允許空值的地圖結構,這通常不是一個好的做法,因爲您無法區分該項目不存在或爲空 – dfb

+0

@dfb:感謝您的答案。但我還沒有了解地圖。所以,如果你可以用另一種方法來指導我,那將是非常有幫助的 – clarkson

0

我希望我不會爲你解決一些學校作業或鍛鍊。在這種情況下,你不應該使用它!

該解決方案不使用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))