如何解决使用 LinkedLists 在 Java 中添加多项式
我正在尝试开发一个使用 Java 中的 LinkedList 数据结构添加两个多项式的程序。 截至目前,我有 Node 类
public class Node {
/**
* Term instance.
*/
Term term;
/**
* Next node in linked list.
*/
Node next;
/**
* Initializes this node with a term with given coefficient and degree,* pointing to the given next node.
*
* @param coeff Coefficient of term
* @param degree Degree of term
* @param next Next node
*/
public Node(float coeff,int degree,Node next) {
term = new Term(coeff,degree);
this.next = next;
}
}
这个类只是为LinkedList的节点建立类。我也已经建立了所有相关的类。
我面临的问题是我的加法代码(在下面概述)返回了两个相加的多项式,不包括最后一项(见下文)。 >
添加代码
public static Node add(Node poly1,Node poly2) {
poly1 = reverse(poly1);
poly2 = reverse(poly2);
Node new_Node = new Node(0,null);
Node head = new_Node;
while(poly1.next != null && poly2.next != null){
//If power of 1st polynomial is greater then 2nd,then store 1st as it is and move its pointer
if(poly1.term.degree > poly2.term.degree){
new_Node.term.degree = poly1.term.degree;
new_Node.term.coeff = poly1.term.coeff;
poly1 = poly1.next;
}
// If power of 2nd polynomial is greater than the 1st,then store the 2nd as it is and move its pointer
else if(poly1.term.degree < poly2.term.degree){
new_Node.term.degree = poly2.term.degree;
new_Node.term.coeff = poly2.term.coeff;
poly2 = poly2.next;
}
// If power of both polynomials are the same,then add their coefficients
else {
new_Node.term.degree = poly1.term.degree;
new_Node.term.coeff = poly1.term.coeff + poly2.term.coeff;
poly1 = poly1.next;
poly2 = poly2.next;
}
// Creates new node
new_Node.next = new Node(0,null);
new_Node = new_Node.next;
}
while(poly1.next != null || poly2.next != null) {
if(poly1.next != null){
new_Node.term.degree = poly1.term.degree;
new_Node.term.coeff = poly1.term.coeff;
poly1 = poly1.next;
}
if(poly2.next != null){
new_Node.term.degree = poly2.term.degree;
new_Node.term.coeff = poly2.term.coeff;
poly2 = poly2.next;
}
new_Node.next = new Node(0,null);
new_Node = new_Node.next;
}
//Returns the new polynomial
return head;
}
如果我喂两个链表
4x^5 - 2x^3 + 2x + 3
8x^4 + 4x^3 - 3x + 9
这会返回我的总和
0.0 + -1.0x + 2.0x^3 + 8.0x^4 + 4.0x^5
这缺少正12的第一项(列表颠倒了)
谁能帮我解决这个问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。