【问题标题】:Linked list method changes other list (Java)链表方法更改其他列表(Java)
【发布时间】:2014-01-29 18:11:46
【问题描述】:

我编写了一个类,它使用链表表示多项式(该列表中的成员是我创建的另一个名为 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;
}

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

【问题讨论】:

  • 我没有深入阅读代码,但是您正在更改 curr2,它最初是参数的头部。您的问题可能与此有关。
  • 能否请您参考我正在更改 curr2 的行?
  • 我不知道确切的行,但你有“curr2=curr2.getNext();”在 2 个不同的地方。用 ctrl+f 检查 curr2 你会看到的。

标签: java linked-list polynomial-math


【解决方案1】:

你有这行: PolyNode curr=_head, curr2=other._head 您在那里所做的是对 _head 和 other._head 的引用(引用是对它们的内存地址)。 因此,当您更改对象时,具有相同内存地址的所有对象也将被更改。 如果您希望它们不被更改,则需要在内存中为它们分配一个新地址。 你可以这样做:

PolyNode curr = new PolyNode(_head)

假设你有一个拷贝构造函数。

【讨论】:

  • 问题是我没有改变curr2,我使用的唯一方法是get方法。
  • 是的,它改变了curr2,但它只改变它指向的地方,而不是other._head
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 2019-04-08
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
相关资源
最近更新 更多