小白用java写的多项式加乘(现在明白java里面出现null就会报错)
public class multiList {
public static class ListNode {
int coef; //系数
int exp; //指数
ListNode Next;
ListNode(int coef,int exp){
this.coef=coef;
this.exp=exp;
}
}
public static ListNode mult(ListNode p11,ListNode p22) throws Exception {
if(p11==null||p22==null) { //相乘多项式不能为0
throw new Exception();
}
ListNode p1=p11;
ListNode p2=p22;
ListNode rear = new ListNode(0,0);
ListNode front=rear; //初始化队列头尾指针
int c,e; //临时变量:系数,指数
while(p2 != null) { //先将P1里的第一个数和P2多项式相乘得到一个多项式
c=p1.coef*p2.coef;
e=p1.exp+p2.exp;
rear=attach(c,e,rear);
p2=p2.Next;
}
p1=p1.Next;
while(p1!=null) { //将P1的每个数和P2相乘,每次循环P2链表和目标乘积多项式应该回到最前面
rear=front;
p2=p22;
while(p2!=null) {
c=p1.coef*p2.coef;
e=p1.exp+p2.exp;
while(rear.Next!=null&&e<rear.Next.exp) { //找到插入位置
rear=rear.Next;
}
if(rear.Next!=null) { //判断是否是链表尾部
if(e==rear.Next.exp) { //判断指数是否相等,相等合并
if((c+rear.Next.coef)!=0) //判断系数相加是否为0
rear.Next.coef=c+rear.Next.coef;
else
rear.Next=rear.Next.Next;
}
else { //指数不相等插入
ListNode p = new ListNode(c,e);
p.Next=rear.Next;
rear.Next=p;
}
}
else { //插在链表尾部
ListNode p = new ListNode(c,e);
rear.Next=p;
}
p2=p2.Next;
}
p1=p1.Next;
}
return front.Next;
}
public static ListNode polyAdd(ListNode p1,ListNode p2) throws Exception {
ListNode rear = new ListNode(0,0); //队列尾指针
ListNode front=new ListNode(0,0); //队列头指针
int e,sum;
front=rear;
if(p1==null && p2==null) {
throw new Exception("The two Lists is empty,can't add ");
}
while(p1!=null && p2!=null) { //链表不为空
e=p1.exp-p2.exp; //比较两个链表第一个元素指数大小
if(e>0) {
rear=attach(p1.coef,p1.exp,rear); //把大的链表赋给队列尾指针,链表后移
p1=p1.Next;
}
else if(e<0) { //否则宁外一个链表
rear=attach(p2.coef,p2.exp,rear);
p2=p2.Next;
}
else { //指数相同,底数相加
sum=p1.coef+p2.coef;
if(sum!=0) { //不为0的话加到队列后面,两个链表指针都要后移
rear=attach(sum,p2.exp,rear);
p1=p1.Next;
p2=p2.Next;
}
}
}
if(p1==null) //将剩下的链表加到队列后面
rear.Next=p2;
else
rear.Next=p1;
return front.Next;
}
public static ListNode attach(int coef,int exp,ListNode pRear){ //添加元素到队列链表后面
ListNode p = new ListNode(0,0);
p.coef=coef; //赋值
p.exp=exp;
pRear.Next=p; //指针后移
return p;
}
private static void printList(ListNode list1) {
if(list1==null||list1.Next==null) {
return ;
}
while(list1!=null) {
System.out.print(list1.coef);
System.out.print(" ");
System.out.print(list1.exp);
System.out.println();
list1=list1.Next;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode n1= new ListNode(3,3);
ListNode n2= new ListNode(-2,1);
ListNode n3= new ListNode(5,0);
n2.Next=n3;
n1.Next=n2;
//List m1
ListNode m1= new ListNode(2,5);
ListNode m2= new ListNode(4,4);
ListNode m3= new ListNode(3,3);
ListNode m4= new ListNode(1,2);
m3.Next=m4;
m2.Next=m3;
m1.Next=m2;
try {
printList(mult(n1,m1));
printList(polyAdd(n1,m1));
}catch(Exception e){
System.out.print("The two Lists is empty,can't mult");
}
}
}