1

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;
    }
}

1 Answers1

1

I think what you need is to convert the data element in the ListNode Class from the type T to be an array or list of T

Sherif Tarek
  • 169
  • 1
  • 8
  • Wouldnt this impose a restriction on the type of contents in the node? Fpr example, if I need 5 integers and 1 float, it'll be an issue. – Umair Chaudhry Mar 18 '19 at 19:48
  • You can create a single `interface` and create your own Types (`classes`) that implements this `interface`. There's a built-in one, you can find it here: https://stackoverflow.com/questions/23957581/java-array-with-multiple-data-types/23957635 – Sherif Tarek Mar 18 '19 at 22:39