2014-01-29 4 views
1

연결된 목록을 사용하여 폴리 노름을 나타내는 클래스를 작성했습니다 (이 목록의 멤버는 PolyNodes라는 다른 클래스의 개체입니다). 들어연결된 목록 메서드가 다른 목록을 변경합니다. (Java)

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

: 클래스에서 나는 (이 방법은 paramater을 변경하지 않으면 서 두 polynoms 의 합을 반환하는 paramater의 polynom을 얻을 기존 polynom에 추가 할 예정이다)이 방법을 서면으로 작성했습니다 어떤 이유로 (나를 넘어서서),이 메소드를 사용할 때 paramater polynom도 변경됩니다. 변경하지 않고 유지하려고 할 때. 나는 이유가 없다. 누군가 나를 도울 수 있습니까? 나는 여기서 희망을 잃고있다.

+0

코드를 깊이 읽지는 ​​않았지만 처음에는 매개 변수의 머리 인 curr2가 변경되었습니다. 아마도 그 문제가 주위에 있습니다. –

+0

curr2가 바뀌고있는 라인을 나에게 알려주시겠습니까? – Guy

+0

줄을 정확히 모르지만 "curr2 = curr2.getNext();"가 있습니다. 2 개의 다른 장소. ctrl + f를 사용하여 curr2를 확인하십시오. –

답변

0

이 줄은 다음과 같습니다. PolyNode curr=_head, curr2=other._head 여기에서 수행중인 작업은 _head 및 other._head에 대한 참조를 제공합니다 (참조는 해당 메모리 주소 임). 그래서 개체를 변경할 때 동일한 메모리 주소를 가진 모든 개체가 변경됩니다. 변경하지 않으려면 메모리에 새 주소로 할당해야합니다. 이렇게 할 수 있습니다.

PolyNode curr = new PolyNode(_head) 

복사 생성자가 있다고 가정합니다.

+0

문제는 curr2를 변경하지 않기 때문에 내가 사용하는 유일한 메소드는 메소드를 얻는 것뿐입니다. – Guy

+0

getNext() 메소드가 잘못되지 않았다면 curr2가 변경되는 것 같습니다. – Tal87

+0

예, curr2는 변경되지만 점이있는 곳만 변경되고 다른 곳은 변경되지 않습니다 ._head – Guy