想相加两个多项式用,用连接串列去解题,
但相加后,print的值却没跑出来,
是我里面add要回传的l3串列,没插入到n3的节点吗?
import java.util.*;
import java.io.*;
class node{
int con;
int x_number;
node next;
node(int c1,int x1){
this.con=c1;
this.x_number=x1;
this.next=null;
}
}
class linkfun{
node first;
node last;
boolean isempty(){
return this.first==null;
}
void insert(node in){
if(this.isempty()){
first=in;
last=in;
}else{
last.next=in;
last=in;
}
}
void print(){
node newnode=first;
while(newnode!=null){
if(newnode.con>0){
System.out.print("+"+newnode.con+"X^"+newnode.x_number);
newnode=newnode.next;
}else if(newnode.con<0){
System.out.print(+newnode.con+"X^"+newnode.x_number);
newnode=newnode.next;
}
}
}
linkfun add(linkfun l1,linkfun l2){
linkfun l3=new linkfun();
node n1,n2,n3;
n1=l1.first;
n2=l2.first;
n3=new node(0,0);
while(n1!=null){
while(n2!=null){
if(n1.x_number==n2.x_number){
n3.con=n1.con+n2.con;
n3.x_number=n1.x_number;
l3.insert(n3);
n1=n1.next;
n2=n2.next;
}else if(n1.x_number>n2.x_number){
n3.con=n1.con;
n3.x_number=n1.x_number;
l3.insert(n3);
n1=n1.next;
}else if(n1.x_number<n2.x_number){
n3.con=n2.con;
n3.x_number=n2.x_number;
l3.insert(n3);
n2=n2.next;
}
}
}
return l3;
}
}
public class NewClass2 {
linkfun list1=new linkfun();
linkfun list2=new linkfun();
linkfun list =new linkfun();
node n1,n2,n3,n4,n5,n6,n7;
node s1,s2,s3,s4,s5,s6,s7;
NewClass2(){
n1=new node(8,8);
n2=new node(54,7);
n3=new node(7,6);
n4=new node(1,4);
n5=new node(3,3);
n6=new node(4,1);
n7=new node(2,0);
s1=new node(-2,9);
s2=new node(6,8);
s3=new node(5,4);
s4=new node(6,3);
s5=new node(8,2);
s6=new node(6,1);
s7=new node(9,0);
}
void a(){
System.out.print("原始多项式1:");
list1.insert(n1);
list1.insert(n2);
list1.insert(n3);
list1.insert(n4);
list1.insert(n5);
list1.insert(n6);
list1.insert(n7);
list1.print();
System.out.println(" ");
System.out.print("原始多项式2:");
list2.insert(s1);
list2.insert(s2);
list2.insert(s3);
list2.insert(s4);
list2.insert(s5);
list2.insert(s6);
list2.insert(s7);
list2.print();
System.out.println(" ");
System.out.print("相加结果:");
list.add(list1,list2);
list.print();
}
public static void main(String args[]) throws IOException{
NewClass2 c=new NewClass2();
c.a();
}
}