单个链接列表在参数Java之后删除对象

时间:2014-04-04 22:20:55

标签: java algorithm singly-linked-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;
}

1 个答案:

答案 0 :(得分:1)

这是伪代码算法。如果你不介意的话,你可以将它翻译成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
;