链接列表方法无法正常工作(java)

时间:2014-01-28 20:34:55

标签: java linked-list polynomial-math

我编写了一个使用链表表示多项式的类(该列表中的成员是我称为PolyNodes的另一个类的对象)。 在那堂课里,我写了这个方法:

public Polynom addNode (PolyNode p)
{
    if (p==null) //if the polynode to be added is null, the same polynom is returned
        return this;

    if (_head==null) //If the head is null, the polynom is empty and the polynode becomes the polynom
    {
        _head=p;
        return this;    
    }

    PolyNode curr = _head, prev = null;
    while(curr != null) //when curr becomes null that means we reached the end of the polynom hence we reached the end of the loop as well
    {
      if (p.getPower() > curr.getPower()) //Upon reaching the first term whose power is lower than p's power
      {    
          p.setNext(curr);

          if (prev == null) //When curr is the polynom's head
            _head = p; 
          else 
          prev.setNext(p);

          return this;
      }

      else if (p.getPower() == curr.getPower()) //If the polynom already has a term with the same power, p's and curr's coefficients are summed up
      {
          curr.setCoefficient(curr.getCoefficient() + p.getCoefficient());
          return this; 
      }    

      prev = curr;
      curr = curr.getNext();  

    }

    //If the method reached outside of the loop then there is no term in the polynom whose power is smaller than p's, and p will become the last term in the polynom
    p.setNext(null);
    prev.setNext(p);
    return this;
}

当我尝试编写addPol()方法时问题就出现了。

public Polynom addPol (Polynom other)
{
    for (PolyNode temp=other._head ; temp!=null ; temp=temp.getNext())
        {
        addNode(temp);
    }

    return this;
}

我无法弄清楚为什么,但我的结果出错了。我经历了几十次代码,仍然找不到任何可能导致问题的东西。 问题如下: 当我打印list1时,我得到:

 -5.0x^20+5.0x^17+4.0x^11+6.0x^8-5.0x^7+16.0x+1.0

当我打印list2时,我得到了

 -3.0x^100+2.0x^17-3.0x^4+4.0x

然而,当我打印list1.addPol(list2)

-3.0x^100-10.0x^20+10.0x^17+8.0x^11+12.0x^8-10.0x^7+32.0x+2.0

如果有人能告诉我是什么导致了这一点,我会非常高兴。提前谢谢。

2 个答案:

答案 0 :(得分:1)

当您将节点添加到新列表时,其属性会更改,因此当您移动到下一个列表时,您将移动到第二个列表中的下一个。

你最好只使用提供的LinkedList类,而不是试图自己重新发明它。

答案 1 :(得分:0)

类似的东西:

    PolyNode copy = new PolyNode();
    copy.setCoefficienttemp.getCoefficient()); 
    copy.setPower(temp.getPower()); 
    addNode(copy);

如上所述,否则temp.getNext()将在原始列表中更改。

有一个类Term + next == PolyNode没有下一个会更抽象。