在java中从LinkedList中删除最后一个节点

在java中从LinkedList中删除最后一个节点,java,linked-list,Java,Linked List,我正在研究一种方法,该方法应该在最后一个节点之前删除该节点,逻辑对我来说似乎很好,但当我尝试在项目中实现它时,它没有成功。(哦,我正在使用我的链接列表) 代码如下: public void deleteSec(){ Node current = head; Node p = head.next; Node q = null; while(p.next!=null){ q = current; current.next = p;

我正在研究一种方法,该方法应该在最后一个节点之前删除该节点,逻辑对我来说似乎很好,但当我尝试在项目中实现它时,它没有成功。(哦,我正在使用我的链接列表)

代码如下:

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

那是我自己编的,

假设node类名为node,并且有一个getNext()方法返回下一个节点,如果该节点是最后一个节点,则返回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;
}

如果删除最后一个节点是常见的操作,就像在我的例子中一样,我建议在
节点
构造中添加一个额外的
prev
previous
节点

通常,链接列表节点是

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

这是我想到的,但是我提供的代码有什么问题吗?它不可读。这应该是有意义的,因为我们正在从列表中删除,而不是从节点本身删除。该方法存在许多问题。如果您想使用listIterator对其进行迭代,如果您不知道LinkedList的大小,该怎么办?我想在一次迭代中从末尾删除第n个元素。@SumanthVarada,如果n是从0到n,则只需user.remove(n)或从另一端删除。size()-nI实现了上述代码并随后打印列表,列表最后一行没有任何更改:current.next=q;非当前。下一个=p;我修改了密码
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