【发布时间】:2016-12-11 12:08:11
【问题描述】:
我们开始在学校学习列表,但我不太了解它们是如何工作的。作为家庭作业,我们必须编写一个 add 方法,在列表末尾添加一个元素。我不知道为什么,但是当我添加更多节点时,列表只保存前两个。我想知道为什么以及我应该改变什么。这是代码(我不允许更改给定代码的任何内容。我只能创建新方法...)
public class HeadList {
Entry head;
public HeadList() {
head = null;
}
/**
* Appends a new element with value info to the end of this list
* @param info value of the new element
*/
public void add(int info) {
//TODO
Entry node = head;
if (head != null) {
if (node.next == null){
node.next = new Entry(node, null, info);
}
else{
Entry n = node.next;
while(n != null){
n = n.next;
}
node = new Entry(node, null, info);
}
}
else
head = new Entry(null, null, info);
}
@Override
public String toString() {
String out = "[";
if (head != null) {
out += head.elem;
Entry tmp = head.next;
while (tmp != null) {
out = out + "," + tmp.elem;
tmp = tmp.next;
}
}
out += "]";
return out;
}
public static void main(String[] args) {
HeadList l = new HeadList();
l.add(6);
l.add(7);
l.add(8);
l.add(9);
System.out.println("empty list: " + l);
// Test implementation
}
class Entry {
Entry first;
Entry next;
int elem;
public Entry(Entry first, Entry next, int elem) {
this.first = first;
this.next = next;
this.elem = elem;
}
}
}
【问题讨论】:
-
欢迎来到 Stack Overflow!看起来你正在寻求家庭作业帮助。虽然我们对此本身没有任何问题,但请注意这些dos and don'ts,并相应地编辑您的问题。
-
第一次调用add(int info),head为null,通过else语句进入。所有下一个调用,只执行 if。在 if 中,您必须搜索其“下一个”字段为空的最后一个条目 objetc。我希望这可以帮助您找到正确的答案。
-
这也是不正确的:node = new Entry(node, null, info);应该是 node = new Entry(head, null, info);
-
非常感谢您的提示。他们帮助我更好地理解了这个问题。阅读完注意事项后,我会立即修改我的问题。
标签: java linked-list add