簡體   English   中英

參數Java之后的單鏈列表刪除對象

[英]Single Linked List remove object after parameter Java

我目前正在單鏈列表上編寫代碼。 在將對象作為參數傳遞到單個鏈表中之后,如何刪除元素?

這是我刪除列表最后一個元素的方法

public Object removeLast() throws EmptyListException {

    if (head == null) throw new EmptyListException();

    Object o;

    // If there is only one element, we need to modify the head of the list
    if (head.next == null) {
        o = head.content;
        head.content = null;
        head = null;
        return o;
    }

    Node crt = head;
    while (crt.next.next != null)
        crt = crt.next;

    o = crt.next.content;

    // Remove all references that are not needed
    crt.next.content = null;
    crt.next = null;

    return o;
}

這是偽代碼算法。 如果您不介意,則取決於您將其翻譯成Java;)

removeAfter(elem):
    if head == null -> error // empty list

    current = head
    while current != null && current != elem:
        current = current.next
    ;

    if current == null -> error // elem not found
    if current.next == null -> error // no more item after elem

    content = curent.next.content
    current.next = current.next.next
    return content
;

暫無
暫無

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

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