java - Java LinkedList addLast() 方法实现错误
问题描述
所以我在Java中实现了一个单链表。但是,我的 addLast() 方法不断抛出 NullPointerException。
这是错误消息:
线程“main”中的异常 java.lang.NullPointerException:无法分配字段“next”,因为“list.tail”在 SinglyLinkedList.SLinkedList.addLast(SLinkedList.java:39) 的 SinglyLinkedList.SLinkedList.main(SLinkedList.java: 98)
进程以退出代码 1 结束
我不明白为什么 tail 为空。任何帮助,将不胜感激。
这是我的代码
public class SLinkedList {
private SNode head;
private SNode tail;
private static int size;
private static class SNode {
String name;
SNode next;
//constructor
SNode(String name) {
this.name = name;
next = null;
}
}
public static SLinkedList insertNode(SLinkedList list, String name) {
SNode newNode = new SNode(name);
newNode.next = null;
if (list.head == null) {
list.head = newNode;
} else {
SNode last = list.head;
while (last.next != null) {
last = last.next;
}
last,next = newNode;
}
size++;
return list;
}
public static SLinkedList addLast(SLinkedList list, String name){
SNode newNode = new SNode(name);
list.tail.next = newNode;
list.tail = list.tail.next;
size++;
//return the list
return list;
}
// a method that add head to the list
public static SLinkedList addFirst(SLinkedList list, String input) {
SNode newNode = new SNode(input);
newNode.next = list.head;
if (list.head == null) {
list.tail = newNode;
}
list.head = newNode;
size++;
return list;
}
//a method to remove the head of the list
public static String removeFirst(SLinkedList list) throws Exception {
SNode temp = list.head;
// edge cases
// size 0
if (size == 0) {
throw new Exception("The LinkedList is empty.");
}
list.head = temp.next;
temp.next = null;
size--;
// edge cases
// size 0
if (size == 0) {
list.tail = null;
}
return temp.name;
}
public static void printSList(SLinkedList list) {
SNode current = list.head;
System.out.print("Singly LinkedList is: ");
while (current != null) {
System.out.print(current.name + " ");
current = current.next;
}
}
//driver code
public static void main(String[] args) throws Exception {
SLinkedList list = new SLinkedList();
insertNode(list, "nuggie");
insertNode(list, "cloud");
addLast(list, "cotton");
// addLast(list, "jamie");
// addLast(list, "pot-roast");
addFirst(list, "kennedy");
addFirst(list, "hoegaarden");
System.out.println("The element removed is " + removeFirst(list));
System.out.println("Size of the Singly Linked List is " + size);
printSList(list);
}
}
解决方案
您的链表的tail
元素尚未初始化。在里面insertNode
你需要更新你的tail
:
if (list.head == null) {
list.head = newNode;
} else {
SNode last = list.head;
while (last.next != null) {
last = last.next;
}
last.next = newNode;
}
list.tail = newNode; // add this
推荐阅读
- python - 使用pickle加载模式时出现UnicodeDecodeError
- ceres-solver - 类中目标函数的 ceres 求解器的实现
- javascript - 作为类属性的功能组件是 React 中的反模式吗?
- servicestack - 在服务堆栈中创建 Google 登录身份验证
- angular - 注销时如何清空angular4应用程序的缓存
- android-intent - Dialogflow 在区分相似意图方面有多好?
- mysql - 如何从 MySQL 列中的 JSON 文档中获取值?
- c++ - 如何去除黑色背景
- android - Firebase 通知不会在 Redmi Note 8T 上响起
- c++ - 删除 std::string_view 的最后一个字符