簡體   English   中英

雙鏈表,刪除第一次出現

[英]Doubly Linked List, Removing First Occurrence

我在弄清楚如何刪除首次出現的節點時遇到了麻煩。

到目前為止,這里是我刪除第一個出現節點的代碼。

public boolean remove(E doomedElt)
{
    if (head == null)
        return false;

    else if (doomedElt.equals(head.data))
    {
        removeFirst();
        return true;
    }
    else
    {
        DLLNode<E> cursor = head;
        while(cursor.next != null && !cursor.next.data.equals(doomedElt))
            cursor = cursor.next;

        if (cursor.next.next == null && cursor.next.data.equals(doomedElt))
        {
            removeLast();
            return true;
        }
        else
        {
            cursor.next = cursor.next.next;
            cursor.next.next.prev = cursor.prev;  //<---Stuck here.
            cursor.prev = cursor.prev.prev;       //<---And here.

            return true;
        }

    }
}

這是刪除最后一個的代碼:

public E removeLast()
{
    if (tail == null)
        throw new NoSuchElementException("Cannot removeFirst from empty list");
    else if (head == tail)
    {
        E firstOne = head.data;      
        head = tail = null;
        return firstOne;
    }
    else
    {
        E lastOne = tail.data;     
        tail = tail.prev;
        tail.next = null;
        return lastOne;
    }
}

這是首先刪除的代碼:

public E removeFirst()
{
    if (head == null)
        throw new NoSuchElementException("Cannot removeFirst from empty list");
    else if (head == tail)
    {
        E firstOne = head.data;     
        head = tail = null;
        return firstOne;
    }
    else
    {
        E firstOne = head.data;     
        head = head.next;
        head.prev = null;
        return firstOne;
    }
}

當我運行驅動程序時,它將添加(4, 5, 6 ,5, 7, 6) 從那里我告訴它刪除前6 我應該得到一個(4, 5, 5, 7 ,6)以下的.next的鏈接(這我做得到),並按照.prev鏈接我應該得到(6, 7, 5, 5, 4) 相反,我得到(6, 7, 4)

但是,當我刪除cursor.next.next.prev = cursor.prev; cursor.prev = cursor.prev.prev; .prev鏈接返回到原始鏈接,但僅向后。 這意味着我重新連接.prev鏈接的邏輯不正確。

有人可以幫忙重新連接邏輯嗎? prev link,繞過節點。

這個:

cursor.next = cursor.next.next;
cursor.next.next.prev = cursor.prev;  //<---Stuck here.
cursor.prev = cursor.prev.prev;       //<---And here.

應更改為:

cursor.next = cursor.next.next;
cursor.next.prev = cursor;

因為光標是元素刪除之前的位置。 也就是說,如果您有AB和C,並且要刪除B,則A的下一個應成為C,C的前一個應成為A。

請注意,此代碼未經測試,但可以正常工作-如果沒有,請告訴我,我們將為您提供更多幫助。

暫無
暫無

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

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