问题描述
我正在尝试开发一个使用 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 (将#修改为@)