简体   繁体   English

参数Java之后的单链列表删除对象

[英]Single Linked List remove object after parameter Java

I'm currently writing code on Singly Linked Lists. 我目前正在单链列表上编写代码。 How would I remove an element after the object passed in as the parameter in a single linked list? 在将对象作为参数传递到单个链表中之后,如何删除元素?

Here is my method to remove the last element of the list 这是我删除列表最后一个元素的方法

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;
}

Here is the pseudo-code algorithm. 这是伪代码算法。 It's up to you to translate it into Java, if you don't mind ;) 如果您不介意,则取决于您将其翻译成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