我要代表班多項式:代表多項式鏈表
PolyNode(下一個變量):
- INT _電源
- 雙_coefficient
- PolyNode _next
Polynom(與下一個構造函數&法):
- 公共多項式() - 空構造 - 空列表
- 公共多項式(PolyNode P) - 從PolyNode得到PARAM並插入他作爲第一個列表
- 公共多項式ADDNODE上(PolyNode p) - 從PolyNode獲取參數並將其添加到Polynom。 並返回新的多項式
這是測試用例:
// Create two Polynoms
Polynom p1 = new Polynom();
p1.addNode(new PolyNode(0,2));
p1.addNode(new PolyNode(2,4));
System.out.println("\nP1:");
System.out.println(p1);
Polynom p2 = new Polynom(new PolyNode(0,2));
p2.addNode(new PolyNode(2,-1));
p2.addNode(new PolyNode(4,5));
System.out.println("\nP2:");
System.out.println(p2);
這是有用輸出:
P1: 4.0倍^ 2 + 2.0
P2: 5.0x^4-1.0x^2 + 2.0
這是PolyNode I類寫道:
public class PolyNode
{
char _operation;
int _power;
double _coefficient;
PolyNode _next;
public PolyNode()
{
_next = null;
_operation = '+';
_coefficient = 1;
_power = 1;
}
public PolyNode(char oper, double coeff, int power, PolyNode next)
{
_operation = oper;
_coefficient = coeff;
_power = power;
_next = next;
}
public PolyNode(PolyNode next)
{
_next = next;
}
public PolyNode(int power, int coeff)
{
_power = power;
_coefficient = coeff;
}
public void setSign(char oper)
{
_operation = oper;
}
public void setCoef(double coeff)
{
_coefficient = coeff;
}
public void setPower(int power)
{
_power = power;
}
public void setNext(PolyNode next)
{
_next = next;
}
public char getSign()
{
return _operation;
}
public double getCoeff()
{
return _coefficient;
}
public int getPower()
{
return _power;
}
public PolyNode getNext()
{
return _next;
}
public boolean isEnd()
{
return (_next == null);
}
}
這是我寫的多項式類:
public class Polynom
{
private PolyNode _head;
public Polynom()
{
_head = null;
}
public Polynom (Polynom poly)
{
Polynom r = new Polynom (poly);
}
public Polynom (PolyNode p)
{
_head = p;
}
public Polynom addNode (PolyNode p)
{
Polynom r = new Polynom (p);
PolyNode current;
if (_head == null)
_head = p;
else
{
current = _head;
while (current._next !=null)
current = current._next;
current._next = p;
}
return r;
}
public String toString()
{
String s = "";
while (_head != null)
{
s += _head.getCoeff() + "x^" + _head.getPower();
_head = _head._next;
}
return s;
}
}
這是我的錯誤輸出:
P1: 2.0x^04.0x^2
P2: 2.0倍^^0-1.0x^25.0x 4
我不明白鏈表的想法!
的toString()
方法需要這樣的示例輸出:
R = 3.8x10 - 5.9x3 + 5.5x2 - 11.0
將顯示像上的toString():
3.8 x^10 - 5.9 x^3 + 5.5 x^2 - 11。0
希望Java有一個[LinkedList](http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html)類,它將爲您完成存儲工作。 – Riduidel
這可能無法解決所有問題,但在Polynom.toString方法中,您正在重新分配Polynom的_head,這可能不是您想要的。您應該聲明一個局部變量來迭代所有PolyNodes。 – ARRG