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.为什么它会这样做。
答案 0 :(得分:0)
protected static Polynomial head;
您的head
被声明为static
- 因此所有类只有一个副本!创建第二个Polynomial
后,它将覆盖第一个Polynomial head
的头部。
您可能希望它是实例变量而不是类变量。
虽然,这样做也会产生无限递归构造函数调用的问题。要克服它,您可能希望有一个不同的类,其中包含{{1}}作为实例变量,并且每个列表只初始化一次。