简体   繁体   中英

How to have multiple elements in the nodes of a linked list in JAVA

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

我想你需要的是在转换什么data元素在ListNode从类型类T是一个arraylistT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM