[英]Array of Doubly Linked Lists
我想創建一個數組,其中每個元素都是一個雙向鏈表。 這是我到目前為止的內容:
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類中已經實現的方法來提供幫助嗎? 非常感謝。
我不確定要使用哪種邏輯來確定要將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++;
}
請注意,這不是線程安全的。
我對您實際上要完成的事情感到好奇,因為我感覺到您可能會竭盡全力使事情變得復雜。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.