我正在努力研究如何在java中的单链表中创建多个子列表,而不使用java泛型。我已经阅读了溢出的多个问题,其中大多数都实现了泛型来解决问题。基本上我想要一个结构,使链接列表具有Dog,Cat和Snake等值,然后为每个列表创建一个子列表,如:
狗--->贵宾犬,猎犬
|
v
Cat --->西伯利亚
|
v
Snake --->眼镜蛇,Python
我认为我的主要问题在于我的添加方法:
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,我希望能够添加更多。
答案 0 :(得分:1)
我猜你在Animal类中需要以下方法:
public String get(String animal)
{
Node temp = head;
while (temp!=null)
{
if (animal.equals(temp.topList))
{
return temp.botList;
}
temp = temp.next;
}
return null;
}
在主体中它看起来像这样:
public static void main(String args[])
{
Animal list = new Animal();
list.add("Snake", "python,Cobra");
list.add("Dog", "poodle,Retriever");
list.add("Cat", "siberian");
System.out.println(list);
System.out.println(list.get("Dog"));//shows poodle,Retriever
}
答案 1 :(得分:0)
我可能会误解,但似乎你是以一种有点奇怪的方式构建它。你有两个列表:一个是主要类型(狗,猫,蛇),另一个是所有不同的子类型(贵宾犬,猎犬,西伯利亚,眼镜蛇,蟒蛇)。
我认为,相反,第一个列表中的每个项目都应链接到新列表,这意味着您总共有四个列表:
答案 2 :(得分:0)
这样想。
单链表的内容仅包含数据和对链中下一个节点的引用。如果我们将第二个链表视为数据,那么我们可以将节点设计成这样的。
Animal
(狗,猫和蛇)。AnimalType
信息。你不会在这里使用泛型,即使你这样做会更加清洁,但我确实设想过这样的东西:
public class Animal {
private String type;
private AnimalType classification;
// usual constructor and accessor
}
public class AnimalType {
private String typeName;
// usual constructor and accessor
}
public class AnimalNode {
private Animal name;
private AnimalTypeList data;
private AnimalNode next;
// usual constructor, accessor and mutator
}
public class AnimalList { // AnimalList and AnimalTypeList are super similar
private AnimalNode head;
// operations and logic on list
}
public class AnimalTypeList {
private AnimalType head;
// operations and logic on list
}