【发布时间】:2012-10-27 01:45:06
【问题描述】:
我正在开发一个不使用 Java 内置 Linked List 类的程序;我正在从头开始构建它。除了编写将节点插入到链表的特定位置的方法之外,我在所有方面都取得了成功。
我有一个将特定节点设置为“当前”节点的方法。例如,我有一个如下所示的链表:cats --> dogs --> make --> good --> pets,“current”等于2;这意味着“当前”节点是“狗”。
从这里,假设我想在“当前”的位置插入一个新节点,其信息字段为 and。如果操作正确,最终的链表将是:cats --> and --> dogs --> make强> --> 好 --> 宠物; "and" 将替换位置 2 的 "dogs"。
所以这是我的问题:我的方法可以在位置 2 插入一个新节点,但是将新创建的节点链接到预先存在的节点时出现了问题。我不仅将我的新节点插入到列表中,而且还在“dogs”之前插入了一个没有信息的节点。当我的代码当前运行时,输出如下所示:cats --> and --> (空白) --> dogs -- > 制作 --> 好 --> 宠物。
我 99.9% 确定问题出在代码的(如果当前!= null)部分,我只是不知道如何解决它。
除了我实际想要添加的节点之外,我为什么还要插入一个空白节点?
public void insert () {
System.out.println("Please enter the text you wish to insert, or type \"end\" if you are done inserting.");
String theString;
theString = console.nextLine();
while (!theString.equals("end")){
newNode = new Node ();
newNode.info = theString;
newNode.next = null;
if (first == null){
first = newNode;
last = newNode;
} else if (current != null){
Node p = new Node (current.info, current.next);
current.info = newNode.info;
current.next = p;
}
else {
last.next = newNode;
last = newNode;
}
System.out.println("Please enter the text you wish to insert, or type \"end\" if you are done inserting.");
theString = console.nextLine();
}
}
编辑
整个程序很长,但这里有一个“setLine”方法,它将当前设置为用户希望插入节点的任何位置。它接受一个通过用户提示获得的参数“int line”。
public Node setLine(int line) {
int index = 0;
current = first;
while (index < line) {
previous = current;
current = current.next;
index++;
}
return current;
}
【问题讨论】:
-
这种类型的事情你只需要一步一步地完成,通常需要大量的 System.out.println 调用。这确实是一个相当普遍的问题,但您需要自己弄清楚。
-
请注意,您应该怀疑创建第二个新节点的情况——任何插入都只需要一个。
-
什么是
console,java.util.Scanner? -
请发布您的其余代码。
-
是的,如果我们知道“当前”是如何设置的,那将会有所帮助。