java - 在java中使用链表乘多项式

标签 java data-structures linked-list polynomials

这是我使用喜欢的列表乘以两个多项式的代码。它工作正常,但问题是如果我乘以 (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/

相关文章:

c++ - 如何在双向链表上执行深拷贝?

java - 如何获取双击的TreeTableNode?

mysql - innodb数据结构

c++ - 航空公司预订链表程序

data-structures - adt和数据结构之间的区别

language-agnostic - 用于存储重复事件的数据结构?

performance - 使用链式与开放式寻址的哈希表中的缓存性能

java - 使用 Java 编写 iPhone 应用程序

java - 无法在 Linux 上加载 OpenCV - undefined symbol 错误

java - 我如何使用小程序通过 rxtxComm.jar 在 ubuntu 上将数据发送到串口