所以对于一个任务,我需要基本上做一个单向链表,使用2种方法,add(x)
这会在列表末尾添加一个新节点,并且会从末尾添加deleteMin()
该清单Java单链接列表娱乐
底部是我所做的代码。我不断收到错误java.lang.NullPointerException
在66行
里面加(x)的方法在head.next = u;
我已经尝试了几次修改代码来修复这个错误,似乎没有任何工作。
package assignment1;
import java.util.InputMismatchException;
import java.util.Scanner;
public class SLL {
private int item;
private SLL next;
SLL(int x, SLL y){
item = x;
next = y;
}
public static SLL head;
public static SLL tail;
public static int n;
public static void main(String[] args){
boolean x = true;
Scanner user_input = new Scanner(System.in);
System.out.println("A = add element, R = remove element, L = to list items inside Singly-Linked-List, Q = to stop session");
while (x == true) {
String user = user_input.next();
String userLow = user.toLowerCase();
switch (userLow) {
case "a":
System.out.println("Add an integer");
int a;
try {
a = user_input.nextInt();
} catch (InputMismatchException e) {
System.out.println("Incorect input, please input an integer.");
break;
}
System.out.println("");
add(a);
break;
case "r":
deleteMin();
break;
case "l":
//list();
break;
case "q":
x = false;
break;
case "help":
System.out.println("A = add element, R = remove element, L = to list items inside queue, Q = to stop session");
break;
case "?":
System.out.println("A = add element, R = remove element, L = to list items inside queue, Q = to stop session");
break;
default:
System.out.println("Not a recognized command: try 'help' or '?' for a list of commands");
break;
}
}
}
public static void add(int x){
SLL u = new SLL(x, head);
if (n == 0) {
head.next = u; // <<<------------
head.next.next = tail;
} else {
SLL current = head;
for (int i = 0; i < n; i++) {
current = current.next;
}
current.next = u;
current.next.next = tail;
}
n++;
}
public static void deleteMin(){
if (n == 0) {
System.out.println("No elements inside list");
} else if (n == 1) {
head.next = null;
tail.next = null;
n--;
} else {
head.next = head.next.next;
head.next.next = null;
n--;
}
}
}
不要忘记说非常无组织 – 2015-02-12 00:04:34
@KickButtowski我实际上键入了几秒钟之前的东西,因为'u'似乎有点偏移,但是丢掉了。 – Zhedar 2015-02-12 00:07:46