多项式链表+测试程序,如果还是不懂请追问(未详细测试,如果有出错,也希望能说下)
PloyList.java { class PloyList & PloyNode}package com.minram;
/**
* Created by minram on 2017/3/15.
*/
public class PolyList {
/**
* @param head 指向单链表的哨兵节点(头)
* @param current 指向单链表的尾部(尾)
* @param numPoly 多项式的项数
*/
PolyNode head;
PolyNode current;
int numPoly;
public PolyList(){
head = new PolyNode();
current = head;
numPoly = 0;
head.next = null;
}
// Judge Empty ( unEmpty~0 ,Empty~1)
public boolean isEmpty(){
return head.next == null;
}
// Insert a Poly
public void insertPoly(PolyNode node){
this.current.next = node;
this.current = node ;
this.numPoly+=1;
}
// Get the value of PolyList
public double getSum(double X){
PolyNode Tmp = head.next;
double sum = 0;
while(Tmp!=null){
sum+=Tmp.getValue(X);
Tmp=Tmp.next;
}
return sum;
}
@Override // 重写 method :toString e.g. F(x) = x^2.0 + 2.0x^2.0
public String toString(){
StringBuilder s=new StringBuilder("");
StringBuilder a=new StringBuilder("");
StringBuilder i=new StringBuilder("");
StringBuilder theOne=new StringBuilder("");
current=head.next;
if(head.next == null ) return null;
else s.append("F(x) = ");
while(current!=null){
a.delete(0, a.length());
i.delete(0, i.length());
theOne.delete(0, theOne.length());
if(current.getCoeff()==1)
a.append("");
else
a.append(String.valueOf(current.getCoeff()));
if(current.getExp()==1)
{
i.append("");
theOne.append(a.toString()).append("x").append(i.toString());
} else{
i.append(String.valueOf(current.getExp()));
theOne.append(a.toString()).append("x^").append(i.toString());
}
if(current==head.next)
s.append(theOne.toString());
else
s.append("+").append(theOne.toString());
current=current.next;
}
return s.toString();
}
}
/**
* @param coeff 项数系数
* @param exp 项数的幂
*/
class PolyNode{
private double coeff;
private double exp;
PolyNode next;
public PolyNode(double _coeff ,double _exp){
this.coeff = _coeff;
this.exp = _exp;
this.next = null;
}
public PolyNode(){
this(0,0);
}
public double getValue(double X){
return this.coeff*Math.pow(X,this.exp);
}
// The method of get & set
public double getCoeff() {
return coeff;
}
public void setCoeff(double coeff) {
this.coeff = coeff;
}
public double getExp() {
return exp;
}
public void setExp(double exp) {
this.exp = exp;
}
}
ProgramTestpackage com.minram;
import java.util.Scanner;
/**
* Created by minram on 2017/3/15.
*/
public class ProgramTest {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("输入多项式长度:");
int length = in.nextInt();
double numCoeff;
double numExp;
double x;
PolyList list = new PolyList();
for(int i = 0;i
System.out.print("输入系数和阶数:");
numCoeff = in.nextInt();
numExp = in.nextInt();
PolyNode Tmp = new PolyNode(numCoeff,numExp);
list.insertPoly(Tmp);
}
System.out.println(list.toString());
System.out.print("输入X的值:");
x= in.nextDouble();
System.out.print("F(x) = "+list.getSum(x));
}
}