2016-11-30 203 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