Pergunta

I've written a class which represents a polynom using a linked list (members in that list are objects of another class I made called PolyNodes). In that class I've written this method:

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;
}

The problem started when I tried writing an addPol() method.

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

    return this;
}

I can't figure out why, but I'm getting wrong results. I went through the code dozens of times and still couldn't find anything that could cause the problem. problem goes as follows: when I print list1 I get:

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

when I print list2 I get

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

however, when I print 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

If anyone could please tell me what is causing this I would greatly appriciate it. thanks in advance.

Foi útil?

Solução 2

Something like:

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

As mentioned, otherwise temp.getNext() will be changed in the original list.

It would be more abstract to have a class Term + next == PolyNode without next.

Outras dicas

When you add the node to a new list its properties get changed, so then when you move onto next you move to the next in the second list.

You would be better off just using the provided LinkedList class for this rather than trying to re-invent it yourself.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top