原多项式为:
A=8X^8 + 54X^7 + 7X^6 + 1X^4 + 3X^3 + 4X + 2
B=-2X^9 + 6X^8 + 5X^4 + 6X^3 + 8X^2 + 6X + 9
多项式相加的结果为:
C=-2X^9 + 14X^8 + 54X^7 + 7X^6 + 6X^4 + 9X^3 + 8X^2 + 10X + 11
数组表示法会有以下困扰:
多项式内容变动时,对数组结构的影响相当大,算法处理不易。
由于数组时静态数据结构,所以事先必须查找一块连续的并且够大的内存空间,容易造成内存空间的浪费。
则此时使用单向链表来表示多项式,就可以克服以上的问题。
package linkList;
class Node2{
int coef;//表示该变量的系数
int exp;//表示该变量的指数
Node2 next;//指向下一节点的指针
public Node2(int coef,int exp) {
this.coef=coef;
this.exp=exp;
this.next=null;
}
}
class PolylinkedList{
public Node2 first;
public Node2 last;
public boolean isEmpty() {
return first==null;
}
public void creat_link(int coef,int exp) {
Node2 newNode=new Node2(coef,exp);
if(this.isEmpty()) {
first=newNode;
last=newNode;
}else {
last.next=newNode;
last=newNode;
}
}
public void print_link() {
Node2 current=first;
while(current!=null) {
if(current.exp==1&¤t.coef!=0) {
System.out.print(current.coef+"X + ");
}else if(current.exp!=0&¤t.coef!=0) {
System.out.print(current.coef+"X^"+current.exp+" + ");
}else if(current.coef!=0) {
System.out.print(current.coef);
}
current=current.next;
}
System.out.println();
}
public PolylinkedList sum_link(PolylinkedList b) {
int sum[]=new int[10];
int i=0,maxnumber;
PolylinkedList templinkedList=new PolylinkedList();
PolylinkedList a=new PolylinkedList();
int tempexp[]=new int[10];
Node2 ptr;
a=this;
ptr=b.first;
while(a.first!=null) {
b.first=ptr;
while(b.first!=null) {
if(a.first.exp==b.first.exp) {
sum[i]=a.first.coef+b.first.coef;
tempexp[i]=a.first.exp;
a.first=a.first.next;
b.first=b.first .next;
i++;
}else if(b.first.exp>a.first.exp) {
sum[i]=b.first.coef;
tempexp[i]=b.first.exp;
b.first=b.first.next;
i++;
}else if(a.first.exp>b.first.exp) { sum[i]=a.first.coef;
tempexp[i]=a.first.exp;
a.first=a.first.next;
i++;
}
}
}
maxnumber=i-1;
for(int j=0;j


