2017-11-28 19 views
1

내 코드를 실행할 때마다 프로그램이 영원히 계속 될 때마다 연결된 목록의 모든 항목이 완벽하게 작동합니다. 삭제를 포함하여링크 된 목록에서 가장 작은 값을 찾는다.

public Node smallestValue() { 
    Node current = firstL; 
    int min = current.data; 

    if (!isEmpty()) { 
     while (current != null) { 
      if (min < current.data) { 
       min = current.data; 
       current = current.next; 
      } 
     } 
    } else { 
     System.out.println("empty list"); 
    } 

    System.out.println(); 
    System.out.println(min); 

    return current; 
} 
+3

'current = current.next'를'if' 문 밖으로 옮깁니다. – Oswald

+1

그리고 조건이 잘못되었습니다. 'if (min> current.data)'이어야합니다. – 0x499602D2

답변

2

당신은 current 여부 min < current.data을 진행해야합니다. 과제를 if 외부로 이동하십시오. (0x499602D2 코멘트에서 지적 @으로서 또한, 당신이 current.data보다 min을 변경해야 할 가장 작은 값을 찾을 수 있습니다.)

while(current != null){ 
    if(min > current.data){ 
     min = current.data; 
    } 
    current = current.next; 
} 

for 루프로이 작업을 수행하는 청소기 수 있습니다 이 빈 목록에 대한 테스트의 내부에 있기 때문에 firstLnull 경우,이 충돌하지 않는 장점이있다

for (Node current = firstL, int min = current.data; 
    current != null; 
    current = current.next) 
{ 
    min = Math.min(min, current.data); 
} 

(목록이 비어 있지 않은 경우 내가 생각하는, 일어나지 않을 수 있습니다.)

+0

아 감사합니다! 이제 작동합니다. – abc123