使用链表的Java多项式加法

时间:2015-09-29 03:50:48

标签: java data-structures linked-list polynomial-math

我正在尝试使用链接列表添加两个多项式,但我的结果总是为0.0,我不知道为什么。我出错了什么想法,或者我是否采取了正确的方法?

-poly是指向存储多项式的链表前面的指针,在代码的不同部分初始化为null

    public Polynomial add(Polynomial p) {
    Polynomial a = this; 
    Polynomial sum = new Polynomial();
    sum.poly = new Node (0,0,null);
    Node c = a.poly;
    Node d = p.poly; 

    while(c!=null || d!=null ){ //either list still has entries 
        if(c == null){
            sum.poly.term = d.term;
            d=d.next; 

        } else if(d == null){
            sum.poly.term = new Term(c.term.coeff, c.term.degree);
            c=c.next; 

        } else if(c.term.degree > d.term.degree){
            sum.poly.term = c.term;
            c=c.next; 

        } else if(d.term.degree > c.term.degree){
            sum.poly.term = d.term;
            d=d.next; 
        }
        else{ // degrees are the same so we add 

            float temp = d.term.coeff + c.term.coeff;
            c=c.next;
            d=d.next;
            if(temp ==0){ 
                continue; // do not store 
        }
            sum.poly.term = new Term (temp, c.term.degree);
        }

        sum.poly.next = new Node(0,0,null);
        sum.poly = sum.poly.next;  
    }
    return sum;
}

0 个答案:

没有答案