繁体   English   中英

删除singleLinked列表中的最后一个元素

[英]Delete last element in singleLinked List

我正在制作一个简单的链表,并且试图实现一种允许删除链表的最后一个节点的方法。 在某些时候,我的方法是错误的,我不确定错误在哪里以及如何解决。 这是代码!

public Nodo deleteEnd() {

    Nodo aux;
    if (head == null) {
        throw new NoSuchElementException("Element cant be deleted");

    } else {

        aux = head;

        while (aux.next.next != null) {
            aux = aux.next;
        }

        size--;
    }
    return aux;
}

您需要将最后但并非最不重要的节点的next分配为null

if(head.next == null) {
    // head is last!
    head = null;
    size = 0;
} else {
    previous = head;
    current = head.next;
    // while current is not last, keep going
    while(current.next != null) {
       previous = current;
       current = current.next;
    }
    // current is now on last!
    previous.next = null;
    size--;
}

尝试减少一个.next

    while (aux.next != null) {
        aux = aux.next;
    }
public Nodo deleteEnd() {
    if (head == null) {
        throw new NoSuchElementException("Element can't be deleted");
    }
    Nodo current = head;
    Nodo next = current.next;

    // Check if there is only the head element.
    if ( next == null )
    {
        size--;
        head = null;
        return current;
    }

    // Skip to the end.
    while (next.next != null) {
        current = next;
        next = next.next;
    }

    // Break the link to the next element.
    current.next = null;
    size--;
    return next;
}

aux.next = null;

在while循环之后-那么将没有对最后一个元素的引用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM