java - 将两个在java中存储为链表的多项式相加

标签 java algorithm linked-list

我有一个单项式结构,它将三个变量的系数和指数作为一个数字。我的单项式类如下所示:

public class Monomial {
private Float coeff;
private Integer exp;
private Integer x,y,z;

public Monomial() {
    this.coeff=null;
    this.x=this.y=this.z=null;
    this.exp=null;
}

public Monomial(Float coeff, Integer x, Integer y, Integer z) {
    this.coeff = coeff;
    this.x = x;
    this.y = y;
    this.z = z;
    this.exp = (100*x)+(10*y)+z;
}

public Monomial(Integer exp) {
    this.exp = exp;
    this.x=(exp-(exp%100))/100;
    this.z = exp%10;
    this.y = ((exp-z)/10)%10;
}

public Monomial(Float coeff, Integer exp) {
    this.coeff = coeff;
    this.exp = exp;
    this.x=(exp-(exp%100))/100;
    this.z = exp%10;
    this.y = ((exp-z)/10)%10;
}

}

我的多项式类存储为单项式的链接列表。

我想添加 2 个多项式。这是我的加法函数

public Polynomial addition(Polynomial a, Polynomial b) {
    LinkedList<Monomial> Main = new LinkedList<>();
    LinkedList<Monomial> temp1 = a.getPolynomial();
    LinkedList<Monomial> temp2 = b.getPolynomial();
    for(int i = 0;i<temp1.size();i++){
        for(int j = 0;j<temp2.size();j++){
            Integer c1= temp1.get(i).getExp();Integer c2 = temp2.get(j).getExp();
            if(c1.equals(c2)){
                Float k1 = temp1.get(i).getCoeff();Float k2 = temp2.get(j).getCoeff();
                Main.add(new Monomial( k1+k2,temp2.get(j).getExp()));
                //temp1.remove(i);temp2.remove(j);
            }
            else if(!c1.equals(c2)){
                Main.add(new Monomial(temp1.get(i).getCoeff(),temp1.get(i).getExp()));
                //temp1.remove(i);
                Main.add(new Monomial(temp2.get(j).getCoeff(),temp2.get(j).getExp()));
                //temp2.remove(j);
            }
        }
    }
    Polynomial ret = new Evaluator(Main);
    return ret;
}

我的输入如下所示 多项式1: 10 1 2 3 11 4 5 6 多项式2: 12 1 2 3 13 4 5 6

多项式 1 可以解释为 10x(y^2)(z^3) 等等。

我得到的输出是: 22.0 1 2 3 10.0 1 2 3 13.0 4 5 6 这不是所需的输出。计算未正确执行。我知道我的循环体出了问题,但我不知道它是什么。 我想知道哪里出了问题以及如何纠正。

最佳答案

你的算法完全错误。只需用纸和铅笔看看会发生什么:您对每个单项式处理 n 次,这不是多项式加法的作用。

正确的方法是构建一个方法将单项式添加到现有多项式并迭代添加的多项式。但这还不是全部,只有当所有单独的系数都在 0-9 范围内时,计算单个系数以在单个操作中比较 3 个整数值的技巧才有效......

关于java - 将两个在java中存储为链表的多项式相加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44278138/

相关文章:

algorithm - HashMap 中的简单哈希码误解?

java - 当项目排队到队列对象上时,队列对象保持为空

C 链表删除函数

c++ - (C++ 错误 : pointer being freed was not allocated) for linked lists

java - 动态调用方法

java - 使用 HTTP 请求获取最后一个 JSON 数组元素

java - 使用 Spring Boot 从不同端口提供 REST API 和静态内容

java - 两个应用程序使用 JDBC 连接到 mysql 数据库 : one works,,另一个给出 "The Network Adapter could not establish the connection"

java - 剪刀石头布的可扩展解决方案

c# - 如何将十进制值四舍五入到最接近的 0.05 值?