在链表中的特定位置插入节点,在附加元素时抛出运行时错误



我试图首先让用户输入他想添加的项目数量,然后按相反的顺序添加(追加(。下一步是尝试接受两个输入:将某个整数添加到特定位置,但会引发运行时错误。此外,是否有任何方法可以使代码更可读或更高效?

错误:

Exception in thread "main" java.lang.NullPointerException: Cannot assign field "next" because "<local3>" is null
at Solution.append(Solution.java:37)
at Solution.main(Solution.java:79)

输入:

3
16
13
7
1
2

预期输出:16 13 1 7

输出:~ no response on stdout ~

代码:

public class Solution{

Node head;
static class Node{
int data;
Node next;
Node(int d) {
this.data = d;
next = null;
}
}
public void append(int newData){
Node newNode = new Node(newData);

if(head == null){
head = new Node(newData);
return;
}

newNode.next = null;
Node last = head;

while(last != null) {
last = last.next;
}
last.next = newNode;
return;
}

public void printList(){
Node temp = head;
while(temp != null){
System.out.print(temp.data + " ");
temp = temp.next;
}
}

public void insertAt(Node head, int position, int data){
Node node = new Node(data);
if(head == null) {
head = new Node(data);
return;
}

else if(position == 0) {
node.next = head;
head = node;
return;
}
else{
Node current = head;
for( int j = 0; j < position-1; j++){
current = current.next;
}
node.next = current.next;
current.next = node;
return;
}
}

public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Solution llist = new Solution();
int n = sc.nextInt(); sc.nextLine();
for( int i = 0; i < n; i++) {
int element = sc.nextInt();
if(sc.hasNextLine()) sc.nextLine();
llist.append(element);
}

int data = sc.nextInt(); sc.nextLine();
int position = sc.nextInt(); sc.nextLine();
llist.insertAt(llist.head, position, data);
llist.printList();
}

}

我不完全理解你想做什么。但我建议你可能在你的主屏幕上做一些奖励,这样你就可以按照用户的输入操作了。根据错误类型,我可以猜测,也许用户向节点输入了一些数据,而在您的代码中,程序将该变量视为索引

所以一开始只需要让你的主要内容是这样的:

Scanner sc = new Scanner(System.in);
Solution llist = new Solution();
System.out.println("How many items");
int n=sc.nextInt();
for( int i = 0; i < n; i++) {
System.out.println("Enter the element");
int element = sc.nextInt();
System.out.println("Enter the index");
int index=sc.nextInt();
llist.append(element);
}

并继续使用您的代码的其余部分

异常消息指向问题:

Node last = head;
while(last != null) { // loop ends when last == null
last = last.next;
}
last.next = newNode; // accessing property of a null object -> NPE

而循环很可能应该是:

while(last.next != null)

相关内容

最新更新