I am struggling a bit on how to make multiple sub-lists in a singly-linked list in java, without using java generics. I've read through multiple questions in overflow and most of them implement generics to solve the problem. Essentially I want a structure that makes a linked list with values such as Dog, Cat, and Snake and then make a sub-list for each such as:
Dog ---> Poodle, Retriever
|
v
Cat ---> Siberian
|
v
Snake ---> Cobra, Python
I believe my main problem is in my add method:
public void add(String topList, String botList)
{
head = new Node(topList, botList, head);
}
Where topList: [Dog, Cat, Snake] and botList:[Poodle,Retriever, Siberian, Cobra,Python].
I feel like with this addMethod im just branching off my head node into two different Lists and not actually linking my topList with elements of my botList.
I have also tried:
public void add(String topList, String botList)
{
head = new Node(topList, head);
head = new Node(botList, topList);
}
But I'm pretty sure that didn't work since I have two String variables in my void add method.
So my question is how would I go about linking my topList elements with my botList elements? Any help or references would be much appreciated.
This is what i have so far:
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);
}
}
The output is somewhat the one desired, but i know i didn't linked the two lists together. Also i am only able to add one name to the botList and i want to be able to add more.