Java用单链表实现多项式加减乘
用单链表来实现多项式的加减乘,除就不做了,代码如下
publicclassPolynomial{
privateMonomialfirst;//首项
//添加单项式
publicvoidappend(Monomialmonomial){
if(monomial==null){
//donothing
}elseif(first==null){
first=monomial;
}else{
Monomialcurrent=first;
while(current!=null){
//Examda提示:如果指数相同,则相加
if(current.index==monomial.index){
current.coefficient+=monomial.coefficient;
break;
}elseif(current.next==null){//否则直接扔到最后
current.next=monomial;
break;
}
current=current.next;
}
}
}
publicvoidappend(doublec,inti){
append(newMonomial(c,i));
}
publicStringtoString(){
StringBuffersb=newStringBuffer();
Monomialcurrent=first;
while(current.next!=null){
sb
.append(\"(\"+current.coefficient+\"x^\"+current.index
+\")+\");
current=current.next;
}
sb.append(\"(\"+current.coefficient+\"x^\"+current.index+\")\");
returnsb.toString();
}
//两个多项式相加
publicPolynomialadd(Polynomialp2){
Polynomialresult=newPolynomial();
Monomialcurrent=this.first;
while(current!=null){
result.append(current.coefficient,current.index);//Examda提示:注意这里
current=current.next;
}
current=p2.first;
while(current!=null){
result.append(current.coefficient,current.index);
current=current.next;
}
returnresult;
}
//两个多项式相减this-p2
publicPolynomialsubstract(Polynomialp2){
Polynomialresult=newPolynomial();
Monomialcurrent=this.first;
while(current!=null){
result.append(current.coefficient,current.index);//注意这里
current=current.next;
}
current=p2.first;
while(current!=null){
result.append(-current.coefficient,current.index);
current=current.next;
}
returnresult;
}
/**
*this*p2
*
*@return
*/
publicPolynomialmultiply(Polynomialp2){
Polynomialresult=newPolynomial();
Monomialc1=this.first;
Monomialc2=p2.first;
while(c1!=null){
while(c2!=null){
result.append(c1.coefficient*c2.coefficient,c1.index
+c2.index);
c2=c2.next;
}
c1=c1.next;
c2=p2.first;
}
returnresult;
}
publicPolynomialdivide(Polynomialp2){
//todo实现相除
returnnull;
}
publicstaticvoidmain(String[]args){
Polynomialp1=newPolynomial();
p1.append(2.2,1);
p1.append(3.3,2);
p1.append(4.111,7);
System.out.println(\"p1:\"+p1);
Polynomialp2=newPolynomial();
p2.append(2.232,5);
p2.append(3.444,6);
p2.append(5.777,1);
System.out.println(\"p2:\"+p2);
Polynomialresult=p1.add(p2);
System.out.println(\"加:\"+result);
result=p1.substract(p2);
System.out.println(\"减:\"+result);
result=p1.multiply(p2);
System.out.println(\"乘:\"+result);
}
}
/**
*单项式
*/
classMonomial{
doublecoefficient;//系数
intindex;//指数
Monomialnext;//后继结点
publicMonomial(){
}
publicMonomial(doublec,inti){
this.coefficient=c;
this.index=i;
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容