package polynomial;
/**
*
* @author Steven
*/
public class Polynomial
{
private float data;
protected static Polynomial head;
private Polynomial link;
/**
* @param args the command line arguments
*/
public Polynomial(float[] data)
{
head = null;
if(data.length == 1)
head = insertAtFront(head, data[0]);
for(int i = data.length-1; i >= 0; i--)
{
System.out.println(head);
head = insertAtFront(head, data[i]);
}
}
public Polynomial(float data, Polynomial link)
{
this.link = link;
this.data = data;
}
public static Polynomial add(Polynomial p, Polynomial p2)
{
if(p.length() > p2.length())
{
while(p.length() != p2.length())
{
insertAtFront(p2, 0);
}
for(Polynomial poly = p; poly != null && p2 != null; poly = poly.link)
{
p2.data = (p2.data + poly.data);
p2 = p2.link;
}
}
else if(p2.length() > p.length())
{
while(p2.length() != p.length())
{
insertAtFront(p, 0);
}
for(Polynomial poly = p; poly != null && p2 != null; poly = poly.link)
{
p2.data = (p2.data + poly.data);
p2 = p2.link;
}
}
else
{
for(Polynomial poly = p; poly != null && p2 != null; poly = poly.link)
{
p2.data = (p2.data + poly.data);
p2 = p2.link;
}
}
return p2.head;
}
public float evaluate(float x)
{
int i = head.length()-1;
float y = 0;
for(Polynomial poly = head; poly != null; poly = poly.link)
{
if(poly.link == null)
y += poly.data;
else
y += (poly.data * (float)(Math.pow(x, i)));
i -= 1;
}
return y;
}
@Override
public String toString()
{
int i = 1;
String polyString = "blank";
for(Polynomial poly = head; poly != null; poly = poly.link)
{
if(polyString.equalsIgnoreCase("blank"))
{
if(poly.data != 0)
polyString = poly.data + "x^" + (poly.length()-i) + " + ";
else if(poly.data == 1)
polyString = "x^" + (poly.length()-i) + " + ";
else
polyString = poly.data + "x^" + (poly.length()-i) + " + ";
}
else
{
if(poly.link == null)
{
if(poly.data != 0)
polyString = polyString + poly.data;
else if(poly.data == 1)
polyString = polyString + "x";
else
polyString = polyString + poly.data + "x^" + (poly.length()-i);
}
else
{
if(poly.data != 0)
polyString = polyString + poly.data + "x^" + (poly.length()-i) + " + ";
else if(poly.data == 1)
polyString = polyString + "x^" + (poly.length()-i) + " + ";
else
;
}
}
i = i + 1;
}
return polyString;
}
public int length()
{
int answer = 0;
for(Polynomial poly = head; poly != null; poly = poly.link)
{
answer++;
}
return answer;
}
private static Polynomial insertAtFront(Polynomial head, float data)
{
return new Polynomial(data, head);
}
}
我有第二个类,它只是一个运行这些方法的程序,当我创建一个新的多项式并运行关联的方法时,一切似乎都成功运行。在我创建一个新的多项式后,第一个多项式采用第二个多项式的值。我不明白 1.第一个创建的多项式的值的去向和 2.为什么它这样做。
protected static Polynomial head;
您的head
被声明为static
- 因此所有类只有一个副本!创建第二个Polynomial
后,它将覆盖第一个的头部。
您可能希望它是一个实例变量,而不是一个类变量。
但是,这样做也会有其无限递归构造函数调用的问题。为了克服它,您可能希望有一个不同的类,该类将Polynomial head
作为实例变量保存,并且每个列表仅初始化一次。