2015-01-05 2 views
-1

Java에서 처음부터 단독으로 링크 된 목록을 만들었습니다. 다음과 같이 코드는 다음과 같습니다Java에서 단일 링크 된 목록 반전

public class SingleLinkedList<Item> 
{ 
private Node head; 
private int size; 

private class Node 
{ 
    Item data; 
    Node next; 

    public Node(Item data) 
    { 
     this.data = data; 
     this.next = null; 
    } 

    public Node(Item data, Node next) 
    { 
     this.data = data; 
     this.next = next; 
    } 
    //Getters and setters 
    public Item getData() 
    { 
     return data; 
    } 
    public void setData(Item data) 
    { 
     this.data = data; 
    } 
    public Node getNext() 
    { 
     return next; 
    } 
    public void setNext(Node next) 
    { 
     this.next = next; 
    } 

} 

public SingleLinkedList() 
{ 
    head = new Node(null); 
    size = 0; 
} 

public void add(Item data) 
{ 
    Node temp = new Node(data); 
    Node current = head; 

    while(current.getNext() != null) 
    { 
     current = current.getNext(); 
    } 

    current.setNext(temp); 
    size++; 
} 

public void add(Item data, int index) 
{ 
    Node temp = new Node(data); 
    Node current = head; 

    for(int i=0; i<index && current.getNext() != null; i++) 
    { 
     current = current.getNext(); 
    } 

    temp.setNext(current.getNext()); 
    current.setNext(temp); 
    size++; 
} 

public Item get(int index) 
{ 
    if(index <= 0) 
    { 
     return null; 
    } 

    Node current = head; 

    for(int i=1; i<index; i++) 
    { 
     if(current.getNext() == null) 
     { 
      return null; 
     } 

     current = current.getNext(); 
    } 

    return current.getData(); 
} 

public boolean remove(int index) 
{ 
    if(index < 1 || index > size()) 
    { 
     return false; 
    } 

    Node current = head; 
    for(int i=1; i<index; i++) 
    { 
     if(current.getNext() == null) 
     { 
      return false; 
     } 

     current = current.getNext(); 
    } 

    current.setNext(current.getNext().getNext()); 
    size--; 
    return true; 
} 

public String toString() 
{ 
    Node current = head.getNext(); 
    String output = ""; 
    while(current != null) 
    { 
     output+=current.getData().toString()+" "; 
     current = current.getNext(); 
    } 

    return output; 
} 

public int size() 
{ 
    return size; 
} 

public void reverse() 
{ 
    Node current = head; 
    Node prevNode = null; 
    Node nextNode; 

    while(current!=null) 
    { 
     nextNode = current.getNext(); 
     current.setNext(prevNode); 
     prevNode = current; 
     current = nextNode; 
     System.out.println(prevNode.getData()); 
    } 

    head = prevNode; 

} 

}

당신이 볼 수 있듯이, 나는 단지 클래스의 역 기능을 추가했습니다.

그러나 실제로 클래스를 사용하여 시도했을 때 역순으로 시도한 후에 NullPointerException을 발생 시켰습니다.

기능을 확인하기 위해 TEST라는 다른 클래스를 사용했습니다.

1 2 3 4 5 
null 
1 
2 
3 
4 
5 
Exception in thread "main" java.lang.NullPointerException 
    at SingleLinkedList.toString(SingleLinkedList.java:129) 
    at TEST.main(TEST.java:20) 

내가 그 복용하지 값 여부를 확인하기 위해 prevNode의 값을 출력하려고 ...하지만은 다음과 같이

public class TEST 
{ 

    public static void main(String[] args) 
    { 
     SingleLinkedList<Integer> list = new SingleLinkedList<Integer>(); 

     list.add(1); 
     list.add(2); 
     list.add(3); 
     list.add(4); 
     list.add(5); 

     System.out.println(list.toString()); 

     list.reverse(); 
     System.out.println(list.toString()); 

    } 
} 

출력은 다음과 같이 코드입니다. 무엇을할까요?

+1

를 작동하고 당신의 SingleLinkedList.java toString() 메소드에 가장 좋은 방법은 종이와 연필을 사용하고 예제를 그리고 포인터가 프로그램의 작업에 따라 어떻게 바뀌는 지입니다. – Henry

+0

나는 그 모든 것을 시도했다. 아무것도 찾을 수 없습니다. 내가 그 일을하고 있지만 아직도 나는 붙어있다. 나 좀 도와 줄 수있어? –

답변

0

실제로 역 분모가 잘 보입니다.

문제점은 toString() 메소드입니다.
새 목록을 만들 때 데이터가 null 인 초기 요소를 만듭니다.
toString 메서드는 첫 번째 요소를 건너 뛰므로 목록을 역순으로 사용하지 않는 한 제대로 작동합니다.
그러나 목록을 반대로하면 해당 null 요소가 마지막 요소가되고 current.getData()이 null 인 경우 해당 마지막 요소에 대해 output+=current.getData().toString()+" ";을 호출하면 NullPointerException이됩니다.

당신은 몇 가지 옵션이 있습니다 :

  1. (즉, 목록의 나머지를 반대하지만, 머리를 동일하게 유지) 먼저 초기 null의 요소를 유지할 수 있습니다 역방향 방법. 이 toString는 변경되지 않고 남아있을 수 있습니다.
  2. 초기 null 요소를 제거하십시오. 그렇다면 toString 메서드는 아무 것도 건너 뛸 필요가 없습니다.

먼저 널 (null) 요소를 유지 :

public void reverse() 
{ 
    Node current = head.getNext(); 
    Node prevNode = null; 
    Node nextNode; 

    while(current!=null) 
    { 
     nextNode = current.getNext(); 
     current.setNext(prevNode); 
     prevNode = current; 
     current = nextNode; 
     System.out.println(prevNode.getData()); 
    } 

    head.setNext(prevNode); 

} 
+0

toString 메서드를 두 경우 모두 사용할 수있게하는 방법은 무엇입니까? –

+0

@abhyuditjain 제안 사항을 추가하십시오. – Eran

+0

당신의 말을 완전히 이해하지 못했지만, 변화를 구현하려고 시도했지만, 이제는 2 가지 문제가 있습니다 : (1) 마지막 노드가 표시되지 않습니다. (2) 변경을 구현하면 역전 후 toString()이 작동합니다. –

0
while(current!=null) 

이것은 사용자의 문제입니다. 마지막 노드에 도달하면 '다음'노드는 실제로 null입니다. 솔루션이 작동합니다 사실은 확실하지 :

시도

while(current!=null&&current.getNext()!=null) 

EDIT로 변경. 라고 루프의 끝에서 조건을 넣어보십시오 : (다시 : /) :

if(current.getNext()==null) 
    break; 

편집

확인 미안 해요 똑바로 생각하지 않았습니다합니다.

if(current.getNext()==null){ 
    current.setNext(prevNode); 
    break; 
} 

실제 nullpointer가 된 toString입니다 : 마지막에 if 문

변화. 여기 당신이 무슨있다 : 현재 포인트는 다음 null로, 그렇지 않으면 당신은 예외가 있기 때문에

변경하면서 조건

while(current != null&&current.getData()!=null) 

에.

정말 고갈되었습니다.

+0

시도했지만 지금은 마지막 노드가 전혀 표시되지 않습니다. –

+0

게시 한 첫 번째 (잘못된) 솔루션을 시도 했습니까? – kirbyquerby

+0

첫 번째 것은 다른 것을하지 않았습니다. 두 번째도 nullpointerexception을 준다 –

0

을 문제는

가 그 아래에보십시오 같은 문제를 들어 미세

public String toString() { 
     Node current = head; 
     String output = ""; 
     while (current != null) { 
//   output += current.getData().toString() + " "; 
      output += String.valueOf(current.getData()) + " "; 
      current = current.getNext(); 
     } 

     return output; 
    } 
+0

Eran은 toString() 메서드를 변경하지 않고 제 문제를 해결했습니다. 어쨌든 고마워. –