如何在java中创建一个get方法,使节点脱离泛型类型
我正在实现一个循环双链接列表数据结构。与单链接列表一样,双链接列表中的节点具有对下一个节点的引用,但与单链接列表不同,双链接列表中的节点也具有对前一个节点的引用
此外,由于列表是“循环的”,因此列表中最后一个节点中的“下一个”引用指向列表中的第一个节点,而列表中第一个节点中的“上一个”引用指向列表中的最后一个节点
我需要帮助启动我的get方法,我一直在四处寻找,但我找不到任何可以帮助我的东西,因为我正在使用泛型类型。我需要返回E,并且每隔一个例子都会以int为例显示它。这是我的密码:
public class DoublyLinkedList<E>
{
private Node first;
private int size;
@SuppressWarnings("unchecked")
public void add(E value)
{
if (first == null)
{
first = new Node(value, null, null);
first.next = first;
first.prev = first;
}
else
{
first.prev.next = new Node(value, first, first.prev);
first.prev = first.prev.next;
}
size++;
}
private class Node<E>
{
private E data;
private Node next;
private Node prev;
public Node(E data, Node next, Node prev)
{
this.data = data;
this.next = next;
this.prev = prev;
}
}
@SuppressWarnings("unchecked")
public void add(int index, E value)
{
if (first.data == null)
{
throw new IndexOutOfBoundsException();
} else if (index == 0)
{
first = new Node(value, first.next, first.prev);
}
else
{
Node current = first;
for (int i = 0; i < index - 1; i++)
{
current = current.next;
}
current.next = new Node(value, current.next, current.prev);
}
}
@SuppressWarnings("unchecked")
public void remove(int index)
{
if (first.data == null)
{
throw new IndexOutOfBoundsException();
}
else if (index == 0)
{
first = first.next;
}
else
{
Node current = first.next;
for (int i = 0; i < index - 1; i++)
{
current = current.next;
}
current.next = current.next.next;
}
size--;
}
我想不出一个开始的方法,但基本上这个方法应该做的是返回列表中指定索引处的元素。如果index参数无效,则应引发IndexOutOfBoundsException
public E get(int index)
{
}
另外,我的remove方法不准确,但我会自己解决这个问题,我只需要帮助我使用get方法
# 1 楼答案
你也可以使用散列映射,你会在固定时间内得到数据
# 2 楼答案
我遇到的另一个问题是,在我的节点类中,我有一个。让我们将其更新为
现在我的getMethod()将如下所示:
# 3 楼答案
我明白了,我只是对这个问题没有得到任何回应感到震惊。不管是哪种方式,我都会写一些评论,这样它就可以指导未来的观众,让他们在这个问题上苦苦挣扎