java.lang.NullPointerException 尝试向循环链表添加元素时
java.lang.NullPointerException when trying to add elements to a circular linked list
我正在尝试向循环链表添加一个元素,但每当我尝试访问该节点时它都会抛出 NullPointerException。这是我的代码:
编辑:我已经阅读了 post 解释 NullPointerExceptions 但没有任何效果。
public class CircularLinkedList<T> {
static private class Node<T> {
public T data;
public Node<T> next;
Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
}
private Node<T> first;
public void addFirst(T x){
if (first.data.equals(null)){
first.data = x;
first.next = first;
}else{
Node<T> second = first;
first.data = x;
first.next = second;
}
}
编辑:我已经用 private Node<T> first = new Node(null, null);
初始化了节点,一直抛出错误。同样与first.data == null
相比,现在它终止了进程。
编辑:完整代码如下:
public class CircularLinkedList<T> {
static private class Node<T> {
public T data;
public Node<T> next;
Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
}
private Node<T> first = new Node(null, null);
public void addFirst(T x){
if (first.data == null){
first.data = x;
first.next = first;
}else{
Node<T> second = first;
first = new Node(x, second);
}
}
public void print() {
while (first.data == null) {
System.out.println(first.data);
first = first.next;
}
}
public static void main(String[] args) {
CircularLinkedList<String> lst = new CircularLinkedList<String>();
lst.addFirst("Z");
lst.addFirst("A");
lst.addFirst("B");
lst.print();
}
}
您在 first.data.equals(null)
语句中得到 NPE,因为最初 first
变量本身是 null
。你必须在开始时像这样初始化它
private Node<T> first = new Node(null, null);
你还必须与 null
进行不同的比较
if (first.data == null) {
我正在尝试向循环链表添加一个元素,但每当我尝试访问该节点时它都会抛出 NullPointerException。这是我的代码: 编辑:我已经阅读了 post 解释 NullPointerExceptions 但没有任何效果。
public class CircularLinkedList<T> {
static private class Node<T> {
public T data;
public Node<T> next;
Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
}
private Node<T> first;
public void addFirst(T x){
if (first.data.equals(null)){
first.data = x;
first.next = first;
}else{
Node<T> second = first;
first.data = x;
first.next = second;
}
}
编辑:我已经用 private Node<T> first = new Node(null, null);
初始化了节点,一直抛出错误。同样与first.data == null
相比,现在它终止了进程。
编辑:完整代码如下:
public class CircularLinkedList<T> {
static private class Node<T> {
public T data;
public Node<T> next;
Node(T data, Node<T> next) {
this.data = data;
this.next = next;
}
}
private Node<T> first = new Node(null, null);
public void addFirst(T x){
if (first.data == null){
first.data = x;
first.next = first;
}else{
Node<T> second = first;
first = new Node(x, second);
}
}
public void print() {
while (first.data == null) {
System.out.println(first.data);
first = first.next;
}
}
public static void main(String[] args) {
CircularLinkedList<String> lst = new CircularLinkedList<String>();
lst.addFirst("Z");
lst.addFirst("A");
lst.addFirst("B");
lst.print();
}
}
您在 first.data.equals(null)
语句中得到 NPE,因为最初 first
变量本身是 null
。你必须在开始时像这样初始化它
private Node<T> first = new Node(null, null);
你还必须与 null
进行不同的比较
if (first.data == null) {