繁体   English   中英

从Java中的LinkedList删除倒数第二个节点

[英]Deleting the second last node from a LinkedList in java

我正在研究一种应该删除最后一个节点之前的节点的方法,这种逻辑在我看来似乎还不错,但是当我尝试在项目中实现该节点时,效果却不佳。 (哦,我正在使用MyLinkedList)

这是代码:

public void deleteSec(){
    Node current = head;
    Node p = head.next;
    Node q = null;

    while(p.next!=null){
        q = current;
        current.next = p;
        p = p.next;
    }
    q.next = p; // q.next = q.next.next;
}

如果您的LL为空怎么办? head将为null,这将在您调用head.next时导致异常。

您必须处理一些特殊情况,例如:空LL,具有一个节点的LL,具有两个节点的LL。

这是我的代码:

public void deleteSec() {
    if (head == null) {
        return;
    }
    if (head.next == null) {
        return;
    }
    if (head.next.next == null) {
        head = head.next;
        return;
    }
    Node current = head;
    Node p = current.next;
    Node q = p.next;
    while (q.next != null) {
        current = current.next;
        p = p.next;
        q = q.next;
    }
    current.next = q;
}
if(myLinkedList.size() > 1) {
    myLinkedList.remove(myLinkedList.size()-2);
}

好吧,我亲自编写了它,

假设节点类名为Node,并且您有一个getNext()方法返回下一个Node,或者如果该Node是最后一个节点,则返回null,您将执行以下操作。

if (head == null) // or if (first == null)
{
return; // There are no elements in the list.
}
Node currect = head; // This is the head, or Node current = first;
Node previous = null;
while (current.getNext() != null)
{
previous = current;
currrent = current.getNext();
}

Then do this to make the second to last pointer to next null.
if (previous != null)
{
previous.setNext( null );
}
else
{
// The list has 1 entry only.
head = null; // or first = null;
}

如果删除第二个最后一个节点将是一个常见的操作,因为它是在我的情况,我建议一个额外的prevprevious加入节点Node建设。

通常一个链表节点是

private static class Node<Item> {
    private Item item;
    private Node<Item> next;
}

但我将其修改为

private static class Node<Item> {
    private Item item;
    private Node<Item> prev;
    private Node<Item> next;
}

因此,如果要删除倒数第二个,实现将非常简单:

oldSecondLast = last.prev; // Assumes last points to the last node
oldSecondLast.next = last;
last = oldSecondLast.prev;
oldSecondLast = null; // To avoid loitering

暂无
暂无

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

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