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;
}
}
,如果你刪除的東西,爲什麼不回你刪除,或者根本不返回任何東西 – OPK
節點'如果(指數<0 ||指數>大小())'應該是'如果(指數< 0 || index> = size())'或最好是'if(!(index> = 0 && index
WalterM
我想我不明白你的任務。爲什麼要創造自己的班級? java.util.LinkedList是雙向的,並實現一個remove()方法,該方法返回被刪除的元素。 https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#remove(int) –