java - 试图找出链表空指针错误的大小
问题描述
对于下面的代码,我想知道为什么链表的大小一直给我一个空指针异常以及为什么我的 pushEnd 方法在最后推送一个新节点不起作用,它在几个节点之后添加一个元素并获取摆脱休息。
class Node {
int data;
Node next;
Node(int data){
this.data = data;
}
}
public class LinkedList {
Node head;
/* Inserts a new Node at front of the list. */
public Node push(int data)
{
Node newNode = new Node(data);
newNode.next = head;
return head = newNode;
}
public Node pushEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
}
newNode.next = null;
while(head != null) {
head = head.next;
head.next = newNode;
return newNode;
}
return head;
}
public int getSize() {
int size = 0;
while(this.head != null) {
size++;
head = head.next;
}
return size;
}
public void printList() {
while (this.head !=null) {
System.out.print(head.data + "-->");
head = head.next;
}
System.out.println(head);
}
}
public class Tester {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
ll.push(35);
ll.push(100);
ll.push(14);
ll.push(44);
ll.push(10);
ll.push(8);
System.out.println("Created Linked list is:");
ll.printList();
System.out.println(ll.getSize());
}
}
我想弄清楚链表的大小并能够在最后添加节点。
解决方案
您的while
循环直接修改head
变量。这会导致您的其他代码失败,因为 nowhead
指向列表中的最后一个节点。
创建一个新的局部变量以在 while 循环中使用(而不是直接修改 head)。那应该解决它!
推荐阅读
- c# - 如何使用 Open XML SDK 读取 xml
- python - 在 x 轴上绘制数据框列
- php - Laravel 通过 Route 将变量从 Form 解析到 Controller 方法
- express - 如何删除这些关于 HEAD 和 OPTIONS 的招摇警告?
- rational-developer-for-i - 如何在 Rational Developer for IBM i 上进行 EDTWRD
- java - 在不知道文件目录或父文件的情况下读取文件路径
- ios - 如何在 swift 中从父子关系中的父子关系中获取子域
- node.js - NestJS:如何注册瞬态和每个 Web 请求提供程序
- android - 如何在 MVVM 架构 android 的云 Firestore 实时更新中包含源缓存
- wordpress - 以编程方式触发 Wordpress Gutenberg “转换为块”