我正在尝试在 java 中删除链表中的节点,但是在尝试使用我的 deletenode() 方法时,我不断收到 NullPointerException。
I get the following error trace:
Exception in thread "main" java.lang.NullPointerException
at linkedlist.LinkedList.deletenode(LinkedList.java:44)
at linkedlist.LinkedList.main(LinkedList.java:69)
/Users/carsongedeus/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53:
Java returned: 1
BUILD FAILED (total time: 3 seconds)
package linkedlist;
import java.util.Scanner;
/**
*
* @author carsongedeus
*/
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
}
public class LinkedList {
Node head;
Node temp;
在列表的头部插入。
public Node insertnode(int data) {
if(head == null) {
head = new Node(data);
} else {
temp = new Node(data);
temp.next = head;
head = temp;
}
return head;
}
在用户在链表的节点内输入指定整数后,Delete 方法给出 NULLPointerException。
public void deletenode(int data) {
Node trace;
Node del;
for(trace = head; trace != null; trace = trace.next) {
if(trace.next.data == data) {
del = trace.next;
trace = trace.next.next;
del.next = null;
}
}
}
打印机
public void printer() {
System.out.println(head.data);
}
public static void main(String[] args) {
LinkedList linkedlist = new LinkedList();
Scanner scan = new Scanner(System.in);
int n;
for(int i = 0; i < (n = (int)(Math.random()*100+1)); i++) {
linkedlist.insertnode((int)(Math.random()*100+1));
linkedlist.printer();
}
System.out.println("Delete something: ");
int input = scan.nextInt();
linkedlist.deletenode(input);
for(int j = 0; j < n; j++) {
linkedlist.printer();
}
}
}
噜噜哒
炎炎设计
相关分类