我正在尝试在java中实现链接列表,但没有任何内容被打印出来。我尝试调试它,似乎每次调用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;
}
}
}
这就是Node类所拥有的
public class Node {
public int data;
public Node next;
}
答案 0 :(得分:0)
你的代码很好。只需去删除* .class文件。它可能会停留在代码的早期阶段。 * .class文件位于输出文件夹下(文件夹的名称可能会根据您使用的IDE而改变,但通常在构建文件夹下。)您可能需要完全删除该文件夹。
答案 1 :(得分: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;
}
}
}