我目前正在学习链表,我发现了编码的基础知识,我完全理解它们。但是,我预设了一定数量的节点,因此用户将无法添加更多节点。如何实现while循环以保持循环并询问用户是否要添加另一条数据。
以下是我目前已有的代码:
public class List {
public int x;
public List ptr = null;
}
上面是List的对象类。 List包含x和指针的数据类型。
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
List front = new List();
front.x = Integer.parseInt(JOptionPane.showInputDialog("Enter a value"));
List l1 = new List();
l1.x = Integer.parseInt(JOptionPane.showInputDialog("Enter a value"));
List l2 = new List();
l2.x = Integer.parseInt(JOptionPane.showInputDialog("Enter a value"));
front.ptr = l1;
l1.ptr = l2;
printNodes(front);
}
public static void printNodes(List p) {
while (p != null) {
System.out.print(p.x + " ");
p = p.ptr;
}
}
}
如您所见,我创建了3个节点,但您无法再添加。我想要有以下几点:
boolean goAgain = true;
while (goAgain) {
//create a new node
String again = JOptionPane.showInputDialog("Add another node?");
if (!again.equalsIgnoreCase("yes")) {
goAgain = false;
}
}
谢谢!
P.S - 我是高中二年级学生,请使用我能理解的词汇。我不会说我是一个java菜鸟,但我也不是专家。答案 0 :(得分:0)
我清理你的while
循环,将所有内容都包含在一个语句中。但那只是因为我懒惰。 ;)
while (!JOptionPane.showInputDialog("Add another node?").equalsIgnoreCase("yes"))
{
//make a new node
}
至于创建新节点的代码,我建议从Java拥有的List
接口实现你的List
类。你可以阅读它here.如果你刚开始使用Java,虽然它可能有点难以理解。作为对现有代码的评论:
List front = new List();
front.x = Integer.parseInt(JOptionPane.showInputDialog("Enter a value"));
您并没有完全按照node
发言,您只需创建List
课程的新实例。在这种情况下,对象被标记为“正面”'我的建议是阅读更多关于List
如何运作的内容。 Here就是一个很好的例子。