我在不使用 java 泛型的情况下如何在 java 中的单链表中创建多个子列表时有些挣扎。我已经阅读了溢出中的多个问题,其中大多数都实现了泛型来解决问题。本质上,我想要一个结构,它可以创建一个包含 Dog、Cat 和 Snake 等值的链表,然后为每个值创建一个子列表,例如:
狗 ---> 贵宾犬,猎犬
|
v
猫 ---> 西伯利亚
|
v
蛇 ---> 眼镜蛇,蟒蛇
我相信我的主要问题在于我的 add 方法:
public void add(String topList, String botList)
{
head = new Node(topList, botList, head);
}
其中 topList:[Dog, Cat, Snake] 和 botList:[Poodle,Retriever, Siberian, Cobra,Python]。
我觉得这个 addMethod 只是将我的头节点分支到两个不同的列表中,而不是实际上将我的 topList 与我的 botList 的元素链接起来。
我也试过:
public void add(String topList, String botList)
{
head = new Node(topList, head);
head = new Node(botList, topList);
}
但我很确定这不起作用,因为我的 void add 方法中有两个 String 变量。
所以我的问题是我将如何将我的 topList 元素与我的 botList 元素链接起来?任何帮助或参考将不胜感激。
这是我到目前为止所拥有的:
import java.util.*;
public class animal
{
Node head;
public animal()
{
head = null;
}
public void add(String topList, String botList)
{
head = new Node(topList, botList, head);
}
public String toString()
{
String x;
StringBuilder sb = new StringBuilder();
Node p = head;
while (p != null)
{
sb.append(p.topList + "\n " + p.botList +"\n");
p = p.next;
}
return new String (sb);
}
public static class Node
{
String topList;
String botList;
Node next;
public Node (String t, String b, Node n)
{
topList = t;
next = n;
botList = b;
}
}
public static void main(String args[])
{
animal list = new animal();
list.add("Snake", "python");
list.add("Dog", "poodle");
list.add("Cat", "siberian");
System.out.println(list);
}
}
输出有点理想,但我知道我没有将两个列表链接在一起。此外,我只能向 botList 添加一个名称,并且我希望能够添加更多名称。