简体   繁体   English

具有Java的列表接口的链接列表数据结构

[英]Linked List data structure with Java's list interface

Suppose we have the following declaration of a Java class Cell<T> used for constructing singly linked lists: 假设我们具有以下用于构造单链接列表的Java类Cell<T>声明:

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> . 问题1.说明由Cell<T>对象组成的链表数据结构如何用于实现Java接口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. 用英语解释(可能还带有图表)就足够了,您无需编写Java代码即可实现该问题。

Attempt (Question 1). 尝试(问题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? 也许如果我们有一个由Cell<T>对象组成的链表数据结构,我们可以使用ArrayList吗?

Question 2. Java's List<E> interface has a method remove with the following signature: 问题2. Java的List<E>接口具有带有以下签名的remove方法:

public E remove(int i)

Write the Java code which gives this method for the implementation described in question 1. 编写Java代码,该代码为问题1中所述的实现提供此方法。

Attempt (Question 2). 尝试(问题2)。 Well because I don't understand question 1, nor could I provide an explanation I don't know how to do this one. 好吧,因为我不明白问题1,也无法提供解释,我不知道该怎么做。

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. 问题3.编写一个Java方法,该方法接受一个表示链接列表的Cell对象,并返回一个数组,该数组的长度为链接列表的长度,并按它们在列表中出现的顺序包含链接列表的元素。

Attempt (Question 3). 尝试(问题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). 解决方案(问题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;
}

1) Think about the meaning of "implementing the interface" - (read the documentation if you need to) - what do you need to do in order to achieve that? 1)考虑一下“实现接口”的含义-(如果需要,请阅读文档)-为了实现这一点,您需要做什么?
2) once you understand Q1) it will not be a problem for you. 2)一旦您了解了Q1),对您来说就不会有问题。
3) Look into iterators 3)研究iterators

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM