2014-01-28 2 views
0

연결된 목록을 사용하여 폴리곤을 나타내는 클래스를 작성했습니다.이 목록의 멤버는 PolyNodes라는 다른 클래스의 개체입니다. 내가 addPol() 메소드를 작성하려고 할 때 문제가 시작연결된 목록 메서드가 제대로 작동하지 않습니다. (Java)

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

: 은 그 클래스에서 나는이 방법을 서면으로 작성했습니다.

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

    return this; 
} 

이유는 알 수 없지만 잘못된 결과가 나타납니다. 나는 수십 번 코드를 훑어 보았지만 여전히 문제를 일으킬만한 것을 찾을 수 없었다. 다음과 같이 문제는 간다 : 나는 list1.addPol (리스트 2)

-3.0x^100-10.0x^20+10.0x^17+8.0x^11+12.0x^8-10.0x^7+32.0x+2.0 
를 인쇄 할 때

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

내가, 내가 그러나

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

를 얻을리스트 2 인쇄 할 때 : 내가 얻을 목록 1 인쇄 할 때

누구든지이 문제의 원인을 알려 주시면 크게 호소 할 것입니다. 미리 감사드립니다.

+1

"디버깅"이 필요합니다. 코드 별 동작을 결정해야합니다 (예 : 문 수준). 디버거라고 불리는 프로그램이 있습니다. 이클립스 나 IntelliJ와 같은 IDE에서 찾을 수 있습니다. Java 개발 환경에 포함 된 (또는 적어도 사용 된) 원시적 인 프로그램도 있습니다. 이러한 매개 변수가 없거나 사용하지 않으려면 코드에 'trace'문을 넣어 여러 지점에서 다른 변수의 값을 확인할 수 있습니다. 우리는 일반적으로 여기 사람들을위한 코드를 디버깅하지 않습니다. – arcy

답변

0

뭔가 : 언급 한 바와 같이

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

, 그렇지 않으면 temp.getNext()는 원래 목록에 변경됩니다.

Term + next == PolyNode 클래스가없는 것은 더 추상적입니다.

+0

나는 <3 너. 이것은 나를 많이 도와 줬다. – Guy

1

노드를 새 목록에 추가하면 속성이 변경되므로 다음으로 이동할 때 두 번째 목록에서 다음으로 이동합니다.

제공된 LinkedList 클래스를 사용하여 직접 다시 작성하는 것이 더 낫습니다. 같은

관련 문제