首页 > 解决方案 > 如何在java中删除链接列表的最后一个节点?

问题描述

我需要在 Java 中实现 LinkedList 的两个方法 removeFirst 和 removeLast

我解决的第一种方法是这样的:

@Override
public E removeFirst() {
    if(isEmpty()){
        throw new NoSuchElementException();
    }
    E element = top.next.data;
    top.next = top.next.next;
    numElements--;
    return element;
}

我在使用 removeLast 方法时遇到问题

     public E removeLast() {
     if(isEmpty()){
         throw new NoSuchElementException();
     }

      for (int i = 0; i < numElements;i++) {


      }

}

我的想法是使用 for 循环来查找最后一个元素,但我不知道在那之后该怎么做

有什么建议么?

我的节点类如下:

public class Node<E> {

E data;
Node<E> next; 

public Node(E data) {
    this(data,null);
}

public Node(E data, Node<E> next) {
    this.data = data;
    this.next = null;
}

@Override
public String toString () {
    return data.toString();


}

}

标签: javadata-structureslinked-list

解决方案


我们必须保持两个指针先前和当前。由于我们记录了列表中元素的数量,我们可以使用 for 循环遍历列表并找到 currentNode 指针指向的最后一个节点和 previousNode 指针指向的前一个节点。最后,将之前的 next 指针更新为 null 并返回 currentNode 数据。

 public E removeLast() {
    if(isEmpty()){
        throw new NoSuchElementException();
    }
    Node previousNode = top;
    Node currentNode = top;
    for (int i = 0; i < numElements -1 ;i++) {
        previousNode = currentNode;
        currentNode = currentNode.next;
    }
    // removed the last element and return the data
    previousNode.next = null;
    numElements-- 
    return currentNode.data;

}


推荐阅读