Java用单链表实现多项式加减乘
用单链表实现多项式的加、减、乘。分了就不干了。代码如下
公类多项式{
私类单项第一;//第一项
//添加一个单项
public void append(单项单项单项){
if(单项= = null){
/do nothing
} else if(first =
} else {
单项当前= first
while(当前!= null){
//exmoda提示:如果指标相同,则添加
If(current . index = = monomial . index){
current . coefficient+= monomial . coefficient;
break;
} else if(current . next = = null){//否则,直接扔到最后
current.next =单项;
break;
}
current = current . next;
}
}
}
public void append(double c,int I){
append(new Monomial(c,I));
}
public String toString(){
String buffer sb = new String buffer();
单项电流=第一;
while (current.next!= null) {
sb
。追加("("+current . coefficient+" x^ "+current . index
+"+");
current = current . next;
}
sb . append("+current . coefficient+" x^ "+current . index+");
return sb . tostring();
}
/Add两个多项式
公共多项式Add(多项式p2) {
多项式result = new多项式();
单项电流= this.first
while(当前!= null){
result . append(current . coefficient,current . index);// Examda提示:此处注意
current = current . next;
}
current = p2 . first;
while(当前!= null){
result . append(current . coefficient,current . index);
current = current . next;
}
返回结果;
}
/从两个多项式中减去this-p2
公共多项式减法(多项式p2) {
多项式结果= new polynomial();
单项电流= this.first
while(当前!= null){
result . append(current . coefficient,current . index);//此处注意
current = current . next;
}
current = p2 . first;
while(当前!= null){
result . append(-current . coefficient,current . index);
current = current . next;
}
返回结果;
}
/* *
* this * p2
*
* @ return
*/
公共多项式乘法(多项式p2) {
多项式结果=新多项式();
单项式c1 = this.first
单项式c2 = 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;
}
返回结果;
}
公共多项式Divide(多项式P2) {
/TODO实现除法
返回null
}
public static void main(String[]args){
多项式p1 = new多项式();
p1.append(2.2,1);
p1.append(3.3,2);
p1.append(4.111,7);
system . out . println(" P1:"+P1);
多项式p2 = new多项式();
p2.append(2.232,5);
p2.append(3.444,6);
p2.append(5.777,1);
system . out . println(" p2:"+p2);
多项式结果= P1 . add(p2);
system . out . println(" plus:"+result);
result = P1 . subtract(p2);
system . out . println(" MINUS:"+result);
result = P1 . multiply(p2);
system . out . println(" multiply:"+result);
}
}
/**
*单项式
类单项{
双系数;//系数
int index;//index
单项next//后继节点
公共单项(){
}
公共单项(double c,int I) {
this。系数= c;
this . index = I;
}
}
0条评论