2013-07-26 2 views
1

삽입 코드는 마지막 삽입까지 완벽하게 작동하는 것처럼 보입니다. 삽입 코드는 목록 끝에 추가하는 대신 순서대로 추가하지 않습니다.사용자 지정 목록에서 반복적으로 삽입 및 제거

public void insert(Comparable item) 
{ 
    if (this.first == null || item.compareTo(this.first.data) <= 0) 
    { 
     addFirst(item); 
    } 
    else if(item.compareTo(this.first.data) > 0) 
    { 
     addLast(item); 
    } 
    else 
    { 
     Node oldFirst = this.first; 
     this.first = this.first.next; 

     insert(item); 

     this.first = oldFirst; 
    } 
} 

이 그것을 생산하는 출력입니다 ...

6 Item(s) 

5 
16 
21 
22 
45 
23 

는 항목을 제거하고 난 이유를 알아낼 수 없습니다 후 제거 방법은 컴파일을 중지

. 이 remove 메소드의 출력입니다

public Comparable remove(Comparable item) 
{ 
    if(this.first == null) 
    { 
     return null; 
    } 

    Node oldFirst = this.first; 

    if(this.first.next == null && this.first.data.equals(item)) 
    { 
     Comparable found = this.first.data; 
     this.first = null; 
     return found; 
    }     

    this.first = this.first.next; 

    if(this.first.data.equals(item)) 
    { 
     Comparable found = this.first.data; 
     oldFirst.next = this.first.next; 
     this.first = oldFirst; 
     return found; 
    } 

    Comparable foundIt = remove(item);  

    return foundIt; 
} 

....

at List.remove(List.java:164) 
Removed: 21. List has: 4 Item(s) 
at List.remove(List.java:164) 

16 
at List.remove(List.java:164) 
22 
45 
at TestRecursion.main(TestRecursion.java:87) 
+0

충돌에 대한 스택 추적은 무엇입니까? –

+0

전체 코드를 넣을 수 있습니까? 그러면 문제를 알려주십시오. –

+0

전체 수업을 볼 수 있습니까? –

답변

0

나는 항목이 귀하의 첫 번째 요소보다 큰 경우의 addLast 전화를 확인할 수 있습니다. 이것은 정렬 된 목록을 제공하지 않습니다.

삽입을 1, 4, 2, 3으로 호출하는 것을 고려하십시오. 출력은 정확히 순서대로됩니다. 1, 4, 왜 제거가 충돌되는 등 또한 3

2 ...

//what if its last item, and the data !.equals(item)? 
if(this.first.next == null && this.first.data.equals(item)) 
{ 
    Comparable found = this.first.data; 
    this.first = null; 
    return found; 
} 
this.first = this.first.next; 
//first could be null here if you are at end of list. 
if(this.first.data.equals(item)) 
{ 
    Comparable found = this.first.data; 
    oldFirst.next = this.first.next; 
    this.first = oldFirst; 
    return found; 
} 

나는 당신이 당신의 디버거를 사용하는 것이 좋습니다. 빨리 물건을 정리해야합니다.

+0

삽입물에 대해 항목 데이터가있는 새 노드를 만든 다음 new.next가 first.next를 가리키고 first.next가 새 노드를 가리 키도록 지정하여이 문제를 해결하려고했지만 작동하지 않습니다. 내가 뭘 잘못하고있어? –

0

귀하의 삽입 방법은 23 마지막

item.compareTo(this.first.data) > 0 

23

때문에 더 참으로 당신의 첫 번째 요소입니다 추가합니다.

0
public void insert(Comparable item) 
{ 
    first = insertRecursively(first, item); 
} 
private static Node insert(Node node, Comparable item) 
    if (node == null || item.compareTo(node.data) <= 0) 
    { 
     Node created = new Node(item); 
     created.next = node; 
     return created;    
    } 
    else 
    { 
     node.next = insertRecursively(node.next, item); 
     return node; 
    } 
} 

재귀 적으로 수행하는 작업은 방금 확인 된 첫 번째/다음을 변경해야합니다.

+0

이제 내가 뭘 잘못하고 있는지 알았어. 고마워. –

관련 문제