我希望创建两个链表并编写一个显示函数,它接受第一个或第二个链表的头作为参数即(一个函数接受第一个列表的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)
主要问题是插入功能。 Java将按值传递参数,这意味着如果更改变量在函数中指向的内容,则不会更改它指向函数外部的内容。
Node head1, head2;
public void insert(Node head, int data) {
Node newNode = new Node(data);
Node temp = head;
head = newNode; // This is changing what the parameter points to!
// Not what the class member points to
newNode.next = temp;
}
你说你想要链接列表中的2个头。我不认为你需要它(2个单独的链表可以工作),但要做到这一点,你可以使用Node
对象的数组。这也允许您修改函数中的头对象:
Node [] heads = new Node[2];
// The head parameter is the index in the heads array
public void insert(int head, int data) {
Node newNode = new Node(data);
newNode.next = heads[head];
heads[head] = newNode; // Works since we are not modifying what the heads member var points to.
// Just modifying it's contents
}
就个人而言,我只会使用一个头部对象。然后你不必将它作为参数传递:
Node head;
public void insert(int data) {
Node newNode = new Node(data);
newNode.next = head;
head = newNode;
}
如果你想要2个列表,那么创建2个LinkedList
对象。
如果display
是head
,null
函数中还会出现一个错误。所以你应该检查一下。