簡體   English   中英

雙鏈表刪除方法

[英]Doubly Linked List Remove Method

嘗試實現一種方法,該方法刪除指定索引處的節點並返回其數據元素。 參加了一個在線初學者課程,我不確定如何返回數據類型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;
    }
}

請記住,對於進入LinkedList的任何數據類型,E都是占位符。 您將像其他任何元素一樣返回數據。 我的建議是,一旦找到要刪除的元素,保存其中的數據,設置新的下一個和上一個引用,然后返回數據。 例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM