我要代表班多项式:代表多项式链表
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