【发布时间】:2019-04-09 18:40:47
【问题描述】:
我希望创建两个链表并编写一个显示函数,该函数接受第一个或第二个链表的头作为参数,即(一个接受第一个列表的 head1 或第二个列表的 head2 的函数)。但是,我'得到一个空指针异常。
package com.main.addtwoele;
public class LinkedList {
Node head1, head2;
public void insert(Node head, int data) {
Node newNode = new Node(data);
Node temp = head;
head = newNode;
newNode.next = temp;
}
public void display(Node head) {
Node temp = head;
System.out.println("---------------Linked List---------------");
if (temp.next == null) {
System.out.println("---Head node----");
System.out.println(temp.data);
}
while (temp.next != null) {
System.out.print(temp.data + "->");
temp = temp.next;
}
System.out.println(temp.data);
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insert(list.head1, 50);
list.insert(list.head1, 40);
list.insert(list.head1, 30);
list.insert(list.head2, 20);
list.display(list.head1);
}
}
Node class is as follows :-
package com.main.addtwoele;
public class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
Exception encountered :
Exception in thread "main" java.lang.NullPointerException
at com.main.addtwoele.LinkedList.display(LinkedList.java:19)
at com.main.addtwoele.LinkedList.main(LinkedList.java:40)
【问题讨论】:
-
insert函数正在修改参数而不是类成员 (head = newNode;)。见:Is Java "pass-by-reference" or "pass-by-value"? -
你为什么有2个头?这可能是一个设计缺陷。为什么不只拥有 2 个单独的
LinkedList对象? -
如何编写插入函数来修改类成员?我不想在插入函数中传递head1或head2作为参数。
-
我有两个头,因为我想将两个链表表示的两个数字相加。