2015-12-28 205 views
1

试图实现一种方法,该方法删除指定索引处的节点并返回其数据元素。采取初学者在线课程,我不知道如何返回数据类型E.对不起,如果我的代码是残酷的。双链表删除方法

public class MyLinkedList<E> extends AbstractList<E> { 
    LLNode<E> head; 
    LLNode<E> tail; 
    int size; 

    /** Create a new empty LinkedList */ 
    public MyLinkedList() { 
     size = 0; 
     head = new LLNode<E>(null); 
     tail = new LLNode<E>(null); 
     head.next = tail; 
     tail.prev = head; 

    public E remove(int index) 
    { 
     int ithNode = 1; //tracks node path location 
     LLNode<E> newNode = new LLNode<E>(null); 

     if (index < 0 || index > size()) { 
      throw new IndexOutOfBoundsException(); 
     } 

     if (index == 1) { 
      newNode = head.next; 
      head.next = null; 
      head.prev = null; 
     } else { 
      while (ithNode != index) { 
       head = head.next; 
       ithNode++; 
      } 
      if (head.next == null) { 
       head.prev.next = null; 
       head.prev = null; 
      } else { 
       head.prev.next = head.next; 
       head.next.prev = head.prev; 
      } 
     } 
    } 

} 

class LLNode<E> 
{ 
    LLNode<E> prev; 
    LLNode<E> next; 
    E data; 

//Not sure if I should create another constructor here 
    public LLNode(E e) 
    { 
     this.data = e; 
     this.prev = null; 
     this.next = null; 
    } 
} 
+1

,如果你删除的东西,为什么不回你删除,或者根本不返回任何东西 – OPK

+0

节点'如果(指数<0 ||指数>大小())'应该是'如果(指数< 0 || index> = size())'或最好是'if(!(index> = 0 && index WalterM

+0

我想我不明白你的任务。为什么要创造自己的班级? java.util.LinkedList是双向的,并实现一个remove()方法,该方法返回被删除的元素。 https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#remove(int) –

回答

0

请记住,E是任何数据类型将进入LinkedList的占位符。你会像任何其他元素一样返回数据。我的建议是,一旦你到达要移除的元素,保存那里的数据,设置新的下一个和上一个引用,然后返回数据。例如:

E returnData = head.data; 
//set references 
return returnData;