使用链表的多项式加法// Java

问题描述

我为我的数据结构课程分配了一个作业。在分配中,我们必须使用链接列表来实现多项式加法。我想我已经失望了,但是日食给了我一个空指针异常。我的问题是与add方法有关,尽管我包括了整个上下文类。乘以后,我将解决。.请帮助。

class polynomialLinkedList{
private static class PNode{
    private int coe;
    private int exp;
    private PNode next;
    public PNode(int c,int e){
        this(c,e,null);
    }
    public PNode(int c,int e,PNode n){
        coe = c;
        exp = e;
        next = n;
    }
    public void setCoe(int c){ coe = c;}
    public void setExp(int e){ exp = e;}
    public void setNext(PNode n){ next = n;}
    public int getCoe(){ return coe;}
    public int getExp(){ return exp;}
    public PNode getNext(){ return next;}
}
private PNode first;
private PNode last;
    public polynomialLinkedList(){
        first = last = null;
    }
    public polynomialLinkedList(int c,int e){
        PNode tempn = new PNode(c,e);
        first = last = tempn;
    }
    public void print(){
        if (first == null){
            System.out.println();
            return;
        }
        PNode temp = first;
        String ans = "";
        while (temp != null){
            if (temp.getCoe() > 0) {
                if (temp != first) ans = ans + " + ";
                ans = ans + temp.getCoe();
            }
            else if (temp.getCoe() < 0) ans = ans + " - " + temp.getCoe() * -1;
            if (temp.getExp() != 0){
                ans = ans + "X^" + temp.getExp();
            }
            temp = temp.getNext();
        }
        System.out.println(ans);
    }
    public polynomialLinkedList add(polynomialLinkedList s){
        polynomialLinkedList sum = new polynomialLinkedList();
        PNode temp1 = this.first;
        PNode temp2 = s.first;
        PNode tempAns = new PNode(0,0);
        if(temp1.exp != temp2.exp) {
            while(temp1.exp > temp2.exp) {
                tempAns.setCoe(temp1.coe);
                tempAns.setExp(temp1.exp);
                temp1 = temp1.getNext();
                tempAns = sum.first.getNext();
            }
            while(temp1.exp < temp2.exp) {
                tempAns.setCoe(temp2.coe);
                tempAns.setExp(temp2.exp);
                temp2 = temp2.getNext();
                tempAns = sum.first.getNext();  
            }
        }
        else if(temp1.exp == temp2.exp) {
            while(temp1.exp == temp2.exp) {
                tempAns.setCoe((temp1.coe + temp2.coe));
                tempAns.setExp(temp1.exp);
                temp1 = temp1.getNext();
                temp2 = temp2.getNext();
                tempAns = sum.first.getNext();
            }
        }
        return sum;
    }
    public polynomialLinkedList multiply(polynomialLinkedList s){
        polynomialLinkedList product = new polynomialLinkedList();
        //implement this method
        return product;
    }

}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)