In my Advanced Data Structures class we have an assignment to implement a linked list using arrays. One array holds the data item, while another contains a reference to the next item. I'm not really sure about how to add/remove items.
// ****************************************************
// Reference-based implementation of ADT list using arrays.
// Due to the limitations with array of generics, the
// "data type" for the list items is fixed to be of type
// PageUsage. Any program using this class must specify
// <PageUsage> as the value for the type parameter.
// ****************************************************
public class List<T> {
// reference to linked list of items
public static final int MAX_LIST = 20;
public static final int NULL = -1;
private PageUsage item[] = new PageUsage[MAX_LIST]; // data
private int next[] = new int[MAX_LIST]; // pointer to next item
private int head; // pointer to front of list
private int free; // pointer to front of free list
private int numItems; // number of items in list
// Constructor must initialize used list to empty and free list to
// all available nodes.
public List()
{
int index;
for (index = 0; index < MAX_LIST-1; index++)
next[index] = index + 1;
next[MAX_LIST-1] = NULL;
numItems = 0;
head = NULL;
free = 0;
} // end default constructor
public void removeAll()
{ // reinitialize all nodes to free
int index;
for (index = 0; index < MAX_LIST-1; index++)
next[index] = index + 1;
next[MAX_LIST-1] = NULL;
numItems = 0;
head = NULL;
free = 0;
} // end removeAll
public boolean isEmpty()
{ // ** YOU IMPLEMENT **
if(head == NULL)
{
return true;
}
else
{
return false;
}
} // end isEmpty
public int size()
{ // ** YOU IMPLEMENT **
int count = 0;
int i = head;
while(i != -1)
{
count++;
i = next[i];
}
return count;
} // end size
private int find(int index)
{ // ** YOU IMPLEMENT **
// --------------------------------------------------
// Locates a specified node in a linked list.
// Precondition: index is the number of the desired
// node. Assumes that 1 <= index <= numItems
// Postcondition: Returns a reference to the desired
// node.
// --------------------------------------------------
for(int i = 0; i <= numItems; i++)
{
if(next[i] == index)
{
return i;
}
}
return -1;
} // end find
public PageUsage get(int index)
{ // ** YOU IMPLEMENT **
return item[find(index)];
} // end get
/* public void add(int index, PageUsage newItem) { // ** YOU IMPLEMENT **
} // end add
public void remove(int index) { // ** YOU IMPLEMENT **
} // end remove*/
} // end List