The relevant code is as follows. The code simply creates a linked list of single elements. I would like to habve multiple elements in each node of the linked list. What changes do I make that allow me to add multiple elements in each node. Right now, the linked list looks like.
------------- -------------
| nodeid: 1 | --> | nodeid: 2 | --> n
------------- -------------
I would want it to look like
------------- -------------
| nodeid: 1 | --> | nodeid: 2 | --> n
| elmts: 5,6| | elmts: 7,9|
------------- -------------
The main class and main method: Takes the size of the list from the user and creates a list of random elements of that size where each element is a node. I want to have a node which is a collection of multiple elements.
public class ListTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int count = input.nextInt();
Random rng = new Random();
List<Integer> list = new List<Integer>();
for(int i = 0; i < count; i++){
list.insertAtBack(rng.nextInt(9));
list.print();
}
}
The List class:
public class List<T> {
private ListNode<T> firstNode;
private ListNode<T> lastNode;
private String name;
public List(){
this("nodelist");
}
public List(String listName){
name = listName;
firstNode = lastNode = null;
}
public void insertAtBack(T insertItem){
if(isEmpty())
firstNode = lastNode = new ListNode<T>(insertItem);
else
lastNode = lastNode.nextNode = new ListNode<T>(insertItem);
}
}
The ListNode class:
class ListNode<T> {
T data;
ListNode<T> nextNode;
ListNode(T object){
this(object, null);
}
ListNode(T object, ListNode<T> node){
data = object;
nextNode = node;
}
}