java - 如何在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();
}
}
解决方案
我们必须保持两个指针先前和当前。由于我们记录了列表中元素的数量,我们可以使用 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;
}
推荐阅读
- php - libxml_use_internal_errors(true) 不会删除所有警告
- php - 如何使用 phpunit 模拟非抽象特征方法?
- mvvm - Xamarin.froms 中用于控制值的滑块
- asp.net-core - 如何在 VS Code 中获取 NuGet 的版本列表和最新版本?
- swiftui - Google 使用 SwiftUI 放置自动完成 API
- sapui5 - 如何在单击时将分段按钮更改为下一个
- .net - 套接字上的线程太慢
- ethereum - 无法在 Ubuntu 16.04 上安装旧版本的 Geth 1.8.27
- .net-core - 如何使用默认的 ITextTemplatingEngineHost 来运行 processTemplate?
- arrays - 如何从具有不同返回类型的 2 个重载函数返回一个值?