所以對於一個任務,我需要基本上做一個單向鏈表,使用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