【问题标题】:Array of Doubly Linked Lists双链表数组
【发布时间】:2015-09-19 05:01:19
【问题描述】:

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

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

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

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

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

我能否以某种方式访问​​我的 doubleLinkedList 类中已经实现的方法来帮助解决这个问题?太感谢了。

【问题讨论】:

  • 你为什么不使用DoublyLinkedList&lt;DoublyLinkedList&lt;E&gt;&gt; listOfLists?您可以通过listOfLists.add(DoublyLinkedList&lt;E&gt; e);listOfList.get(idx).add(E e);listOfLists.get(idx); //returning a DublyLinkedList&lt;E&gt;listOfLists.get(idx1).get(idx2); // returning an element、...访问它们。

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


【解决方案1】:

我不确定您将使用什么逻辑来确定要将 obj 添加到数组的哪个插槽,但这就是您将这样做的方式(当然是在实现 calculateArraySlotSomehow 之后):

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

    listArray[index].add(obj);
}

根据您的 cmets,您可以像这样实现 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++;
}

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

我很好奇你实际上想要完成什么,因为我有一种感觉,你可能会特意把事情复杂化。

【讨论】:

  • 这是有道理的。我该如何计算数组插槽?我有一个 int 大小(数组的大小)和一个 int 限制(双向链表的大小)。我会假设只有一堆条件来检查我是否在这些范围之外添加了一些东西?
猜你喜欢
  • 1970-01-01
  • 2021-06-13
  • 1970-01-01
  • 1970-01-01
  • 2018-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
相关资源
最近更新 更多