链表方法更改其他列表(Java)

时间:2014-01-29 18:11:46

标签: java linked-list polynomial-math

我编写了一个使用链表表示多项式的类(该列表中的成员是我称为PolyNodes的另一个类的对象)。在那个类中我编写了这个方法(这个方法应该得到一个参数多项式并将它加到现有的多项式中,返回两个多项式的总和而不改变参数):

public Polynom addPol(Polynom other)
{
   if (_head==null) //If the head is null, this polynom is empty and 
the other polynom becomes this polynom
   {
       _head=other._head;
       return this;
   }

   if(other._head==null) //if the polynom to be added is null, the
same polynom is returned
        return this;


   PolyNode curr=_head, curr2=other._head, prev=null, prev2=null;

   while(curr!=null && curr2!=null)
   {
      if(curr2.getPower()>curr.getPower())
      {     
          System.out.println("1 " + curr2.getCoefficient());
          PolyNode copy = new PolyNode(curr2.getPower() ,curr2.getCoefficient() );
          System.out.println("2 " + curr2.getCoefficient());
          copy.setNext(curr);
          if (prev==null)
                _head=copy;
          else
                prev.setNext(copy);
      }

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

      //Moving the pointer to the next node in the polynom
      if(curr2.getPower()>curr.getPower())
      {
          prev2=curr2;
          curr2=curr2.getNext();
      }
      else if(curr.getPower()>curr2.getPower())
      {
          prev=curr;
          curr=curr.getNext();
      }
      else if(curr.getPower()==curr2.getPower())
      {
          prev2=curr2;
          curr2=curr2.getNext();
          prev=curr;
          curr=curr.getNext();
      }
   }

   if(curr2!=null) //If there are nodes left in other
   {
       for(;prev!=null;curr2=curr2.getNext()) //add them to this
       {
           PolyNode copy = new PolyNode(curr2.getPower() ,curr2.getCoefficient() );
           prev.setNext(copy);
           prev=curr2;
       }
   }

   return this;
}

出于某种原因(超出我的意义),当我尝试保持它不变时,当我使用这种方法时,参数多项也会改变。我不知道为什么。有人可以帮帮我吗?我在这里失去了希望。

1 个答案:

答案 0 :(得分:0)

你有这条线: PolyNode curr=_head, curr2=other._head 你在做什么是给_head和other._head(引用是他们的内存地址)的引用。 因此,当您更改对象时,所有具有相同内存地址的对象也将被更改。 如果你不想改变它们,你需要在内存中分配一个新地址。 你可以这样做:

PolyNode curr = new PolyNode(_head)

假设您有一个复制构造函数。