Suppose we have the following declaration of a Java class Cell<T> used for constructing singly linked lists:
class Cell<T> {
T first;
Cell<T> next;
Cell(T f, Cell<T> n) {
first = f;
next = n;
}
}
Question 1. Explain how a linked list data structure consisting of Cell<T> objects could be used to implement the Java interface List<E>. An explanation in English, possibly with diagrams, is sufficient, you are not required to write the Java code for the implementation to answer this question.
Attempt (Question 1). No clue where to start with this question to be honest. Maybe if we had a linked list data strucutre consiting of Cell<T> objects we could use an ArrayList?
Question 2. Java’s List<E> interface has a method remove with the following signature:
public E remove(int i)
Write the Java code which gives this method for the implementation described in question 1.
Attempt (Question 2). Well because I don't understand question 1, nor could I provide an explanation I don't know how to do this one.
Question 3. Write a Java method which takes a Cell object representing a linked list and returns an array which is of the length of the linked list and contains the elements of the linked list in the order they occur in the list.
Attempt (Question 3). I was provided with a solution for this question by my teacher but he didn't explain it well enough. So if someone could explain the solution to me that would be great, I don't understand the iteration through the loop part:
for (Cell<T> ptr = list; ptr != null; ptr = ptr.next)
Solution (Question 3).
public static <T> T[] question3(Cell<T> c) {
int count = 0;
for (Cell<T> ptr = list; ptr != null; ptr = ptr.next) {
count++;
}
T[] arr = (T[]) new Object[count];
int i = 0;
for (Cell<T> ptr = list; ptr != null; ptr = ptr.next;i++){
arr[i] = ptr.first;
}
return arr;
}
Aucun commentaire:
Enregistrer un commentaire