Я пытаюсь реализовать двусвязный список . Я реализовал его с двумя контрольными узлами (голова и хвост), реализовал метод добавления, чтобы всегда добавлять в качестве первого элемента в списке, и метод получения, чтобы доставить элемент по указанному индексу c. Проблема в том, что когда я пытаюсь выполнить метод get(index)
, он продолжает получать неправильные ответы. Кто-нибудь может понять, что не так с моей реализацией?
Заранее спасибо.
Это мой код:
public class MyLinkedList<E> extends AbstractList<E> {
LLNode<E> head;
LLNode<E> tail;
int size;
/** Create a new empty LinkedList */
public MyLinkedList() {
// TODO: Implement this method
head = new LLNode<E>(null);
tail = new LLNode<E>(null);
head.next = tail ;
tail.prev=head ;
size = 0;
}
/**
* Appends an element to the end of the list
* @param element The element to add
*/
public boolean add(E element )
{
// TODO: Implement this method
if(element==null) throw new NullPointerException ("NullpointerException") ;
LLNode<E> current = new LLNode<E>(element);
current.next = head.next ;
current.prev = current.next.prev ;
head.next = current ;
current.next.prev = current ;
size++ ;
return true;
}
/** Get the element at position index
* @throws IndexOutOfBoundsException if the index is out of bounds. */
public E get(int index)
{
// TODO: Implement this method.
if(index>size-1 || index<0) throw new IndexOutOfBoundsException("IndexOutOfBoundsException") ;
LLNode<E> theOne = getNode(index) ;
return theOne.data;
}
private LLNode<E> getNode(int index){
LLNode<E> current = head ;
for(int i = 0 ; i<=index ; i++) {
current = current.next ;
}
return current;
}
class LLNode<E>
{
LLNode<E> prev;
LLNode<E> next;
E data;
// TODO: Add any other methods you think are useful here
// E.g. you might want to add another constructor
public LLNode(E e)
{
this.data = e;
this.prev = null;
this.next = null;
}