2016-11-30 111 views
0

我想在java中實現鏈表,但沒有打印出來。我試着調試它,似乎每次調用Add函數時,之前的值都會被寫入。但是,當我檢查它的邏輯,它應該工作。在java中實現鏈接列表

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

這是Node類有

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

這裏是運行'Print'方法的代碼? – ItamarG3

+1

顯示完整的示例。你如何使用它,調用add和print。 – 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

這對你有幫助嗎?請注意或接受有用的建議。 – weston