这是使用链表进行多项式加法的代码。
public class LinkedPolynomial{
private Node first=new Node(0,0);
private Node last=first;
private static class Node{
int coef;
int exp;
Node next;
Node(int coef,int exp){
this.coef=coef;
this.exp=exp;
}
}
private LinkedPolynomial(){}
public LinkedPolynomial(int coef,int exp){
last.next=new Node(coef,exp);
last=last.next;
}
//return c=a+b
public LinkedPolynomial plus(LinkedPolynomial b){
LinkedPolynomial a = this;
LinkedPolynomial c = new LinkedPolynomial();
Node x=a.first.next;
Node y=b.first.next;
while(x!=null || y!=null){
Node t=null;
if(x==null){
t=new Node(y.coef,y.exp);
y=y.next;
}
else if(y==null){
t=new Node(x.coef,x.exp);
x=x.next;
}
else if(x.exp>y.exp){
t=new Node(x.coef,x.exp);
x=x.next;
}
else if {
t=new Node(y.coef,y.exp);
y=y.next;
}
else{
int coef=x.coef+y.coef;
int exp=x.exp;
x=x.next;
y=y.next;
if(coef==0)
continue;
t=new Node(coef,exp);
}
c.last.next=t;
c.last=c.last.next;
}
return c;
}
public static void main (String args[]){
LinkedPolynomial zero=new LinkedPolynomial(0,0);
LinkedPolynomial p1=new LinkedPolynomial(4,3);
}
}
在该方法plus()
中,有人可以向我解释一下做了什么
LinkedPolynomial a = this;
LinkedPolynomial c = new LinkedPolynomial();
Node x=a.first.next;
Node y=b.first.next;
什么是 a.first.next;
是什么LinkedPolynomial
。是节点吗?每个LinkedPolynomial
人都有第一个和最后一个吗?
有人可以向我解释这些。