简体   繁体   中英

Array of Doubly Linked Lists

I would like to create an array where each element is a doubly linked list. Here's what I have so far:

public ArrayOfLists() {
    this.limit = limit;  //limit of Nodes in each element of listArray
    listArray = (DoublyLinkedList<E>[]) new DoublyLinkedList[3];
    listArray[0] = new DoublyLinkedList<E>(); 
    listArray[1] = new DoublyLinkedList<E>();
    listArray[2] = new DoublyLinkedList<E>();
    size = 0;
}

I'm not sure if this is conceptually correct, but I kind of see this as a 2D array. I'm confused with how I go about adding and removing objects from the lists stored in this array. For example,

public void add(E obj) {
    //some stuff
 }

 public void remove(int index) {
    //some stuff
 }

Could I somehow access the already implemented methods in my doublyLinkedList class to assist with this? Thank you so much.

I'm not sure what logic you will use to figure out which slot of the array you want to add your obj to, but this is how you would do it (after implementing calculateArraySlotSomehow of course):

public void add(E obj)
{
    int index = calculateArraySlotSomehow(obj);

    listArray[index].add(obj);
}

Based on your comments, you could implement calculateArraySlotSomehow something like this:

private int calculateArraySlotSomehow(E obj)
{
    // 'count' is the total number of elements that are already
    //         stored in this data structure
    // 'size' is the number of array elements
    // 'limit' is the number of elements per list

    int slot = count / limit;

    if (slot >= size) {
        throw new IndexOutOfBoundsException("Index: " + slot + ", Size: " + size);
    }

    return slot;
}

And then you would have to change your add implementation to:

public void add(E obj)
{
    int index = calculateArraySlotSomehow(obj);

    listArray[index].add(obj);

    count++;
}

Note that this is not thread-safe.

I'm curious as to what you are actually trying to accomplish, because I have a feeling that you might be going out of your way to complicate things.

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