2016-11-30 1 views
0

자바에서 링크 된 목록을 구현하려하지만 아무 것도 인쇄되지 않습니다. 나는 그것을 디버깅 해봤고, Add 함수가 호출 될 때마다 이전 값이 쓰여지는 것처럼 보인다. 그러나 내가 그것의 논리를 확인하면, 그것은 작동합니다.자바에서 링크 된 목록 구현

public class MyLinkedList { 

public Node head; 
public Node curr; 

public MyLinkedList() { 
    // TODO Auto-generated constructor stub 
    head = null; 
    curr = null; 
} 

public void Add(int data) { 
    Node box = new Node(); 
    box.data = data; 
    box.next = null; 
    curr = head; 
    if (curr == null) { 
     head = box; 
     curr = null; 
    } 

    else { 
     while (curr.next != null) { 
      curr = curr.next; 

     } 
     curr.next = box; 
    } 
} 

public void Print() { 
    curr = head; 
    while (curr != null) { 
     System.out.println(curr.data); 
     curr = curr.next; 
    } 
} 
} 

이 노드 클래스는 귀하의 코드는 괜찮

public class Node { 
    public int data; 
    public Node next; 
} 
+1

곳입니다'Print' 방법을 실행하는 코드? – ItamarG3

+1

전체 예제보기. 사용 방법, 추가 및 인쇄 호출. – weston

+0

하나의 노트는 모든 경우에'public Node curr;'은 지역 변수 여야한다는 것입니다. – weston

답변

0

을 가지고 것입니다. 가서 * .class 파일을 삭제하십시오. 그것은 당신의 코드의 초기 단계에서 붙어있을 수 있습니다. * .class 파일은 출력 폴더 아래에 있습니다 (사용하는 IDE에 따라 폴더 이름이 달라질 수 있지만 일반적으로 빌드 폴더 아래에 있음). 해당 폴더를 완전히 삭제해야 할 수도 있습니다.

0

그것은 이미 작동하지만 내가 당신을 위해 그것을 정돈 수 있습니다 :

public class MyLinkedList { 

    private Node head; //never expose a field as public 

    //the whole constructor was unnecessary 

    public void add(int data) { //methods start with a lower case 
     add(new Node(data)); //nodes always need data, so I'm passing in constructor 
    } 

    // this method adds an existing node rather than the previous add both 
    // creating, finding the end and adding 
    private void add(Node node) { 
     if (head == null) { 
      head = node; 
     } else { 
      lastNode().next = node; 
     } 
    } 

    private Node lastNode() { //finds the last node in the chain 
     Node curr = head; //curr is local 
     while (curr.next != null) { 
      curr = curr.next; 
     } 
     return curr; 
    } 

    public void print() { //methods start with a lower case 
     Node curr = head; //curr is local 
     while (curr != null) { 
      System.out.println(curr.data); 
      curr = curr.next; 
     } 
    } 

    private static class Node { //this class is just useful internally to MyLinkedList 
     private final int data; //final - node data doesn't change 
     private Node next; 

     private Node(int data) { 
      this.data = data; 
     } 
    } 
} 
+0

이 도움이 되었습니까? upvote 또는 유용한 제안을 받아주십시오. – weston