原多项式为:
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<maxnumber+1;j++) {
tempLinkedList.creat_link(sum[j], maxnumber-j);
}
return tempLinkedList;
}//end of sum_link
}//end of class PolyLinkedList
public class ch03_05 {
public static void main(String args[]) {
PolyLinkedList a=new PolyLinkedList();
PolyLinkedList b=new PolyLinkedList();
PolyLinkedList c=new PolyLinkedList();
int data1[]= {8,54,7,0,1,3,0,4,2};
int data2[]= {-2,6,0,0,0,5,6,8,6,9};
System.out.print("原多项式为:\nA=");
for(int i=0;i<data1.length;i++) {
a.creat_link(data1[i], data1.length-i-1);
}
//建立多项式A,系数从3递减
for(int i=0;i<data2.length;i++) {
b.creat_link(data2[i], data2.length-i-1);
}
//建立多项式B,系数从3递减
a.print_link();
System.out.print("B=");
b.print_link();
System.out.print("多项式相加的结果为:\nC=");
c=a.sum_link(b);
c.print_link();
}
}