一系列双链表

时间:2015-07-01 20:53:04

标签: java arrays data-structures linked-list doubly-linked-list

我想创建一个数组,其中每个元素都是一个双向链表。这就是我到目前为止所拥有的:

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

我不确定这在概念上是否正确,但我将此视为2D数组。我对如何添加和删除存储在此数组中的列表中的对象感到困惑。例如,

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

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

我可以以某种方式访问​​我的doublyLinkedList类中已经实现的方法来帮助解决这个问题吗?非常感谢。

1 个答案:

答案 0 :(得分:0)

我不确定您将使用什么逻辑来确定要将obj添加到阵列的阵列中的哪个插槽,但这就是您要执行此操作的方法(在实现calculateArraySlotSomehow之后当然):

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

    listArray[index].add(obj);
}

根据您的评论,您可以实现calculateArraySlotSomehow类似的内容:

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

然后您必须将add实施更改为:

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

    listArray[index].add(obj);

    count++;
}

请注意,这不是线程安全的。

我很想知道你究竟想要完成什么,因为我觉得你可能会不顾一切地使事情变得复杂。

相关问题