【发布时间】:2017-01-15 14:48:43
【问题描述】:
我们从课堂上的链表和节点开始,我想我理解它们是如何工作的。但一方面,我们必须将节点添加到链表中,我遇到了一些问题才能让它工作。 错误发生在“追加”方法中。我的 IDE 并没有告诉我太多关于这个问题的信息。
我的班级链表:
public class LinkedList {
public Node head = null;
public void insert(Node n) {
n.next = head;
head = n;
}
public Node search(int nummer) {
Node current = head;
while (current != null) {
if (current.element == nummer)
return current;
current = current.next;
}
return null;
}
public int count() {
int c = 0;
for (Node n = head; n != null; n = n.next) {
c++;
}
return c;
}
public void append(Node n) {
if (head == null){
head = new Node(n, null);
}
else {
Node p = head;
while (p.a != null){
p = (Node) p.a;
}
p.a = new Node(n, null);}
}
}
我的节点类:
public class Node {
public int element = 0;
public Node next = null;
Object a;
public Node(int e, Node n) {
this.element = e;
this.next = n;
}
public Node(int e) {
this.element = e;
}
}
【问题讨论】:
-
您有什么问题?运行代码时会发生什么?结果与您想要的有什么不同?在您的编程生涯中,学习如何调试自己的代码非常重要。您应该使用调试器或添加
System.out.println()语句来帮助您查看代码实际在做什么。我还建议你画图来形象化你在做什么。使用方框或圆圈表示节点,使用箭头表示节点之间的next引用。
标签: java linked-list nodes