我正在实现一个循环 DoublyLinkedList 数据结构。与单链表类似,双向链表中的节点具有对下一个节点的引用,但与单链表不同的是,双向链表中的节点还具有对前一个节点的引用。
另外,因为列表是“循环的”,所以列表中最后一个节点中的“next”引用指向列表中的第一个节点,而列表中第一个节点中的“prev”引用指向列表中的最后一个节点。列表。
我需要帮助来启动我的 get 方法,我一直在环顾四周,但找不到任何可以帮助我的东西,因为我正在使用 Generic Type 。我需要返回 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--;
}
我想不出一种开始的方法,但基本上这个方法应该做的是返回列表中指定索引处的元素。如果索引参数无效,则应抛出 IndexOutOfBoundsException。
public E get(int index)
{
}
另外,我的删除方法不准确,但我会自己解决这个问题,我只需要有关我的获取方法的帮助。