我需要實現一個LinkedList,並且到目前爲止我已經寫了我的方法來在我的列表中插入值。我有我的節點,前面,作爲我的類的實例數據,當創建我的第一個值,並試圖設置在我的新節點旁邊點的值時,我得到一個nullpointerexception。LinkedList NullPointerException(需要幫助實現一個LinkedList)
public class Class1 {
private Node front = null;//Linked List pointer
private int comparisons = 0; //# of comparisons in Lists
//private LinkedList<Node> orderLink = new LinkedList<Node>();
public Class1() {
}
/*public Class1(int x){
}*/
public void insert (int num){
Node current = null;
Node previous = null;
boolean placed = false;
if (front == null){ //generate first node of list
Node first = new Node(num, null);
front.setNext(first);
placed = true;
}
previous = front;
current = front.getNext();
Node step = new Node(num, null);
if (placed == false){
do{
if (step.getData() < current.getData() && step.getData() > previous.getData() || step.getData() == current.getData() || step.getData() == previous.getData()){ //if the new data is between previous and current, place. If equals current, place.
//Insert into List
step.setNext(current);
previous.setNext(step);
placed = true;
}
if (previous == front && step.getData() < current.getData()){ //separate case for first node
step.setNext(current);
previous.setNext(step);
placed = true;
}
if (current.getNext() == null && step.getData() > current.getData()){ //case for last node
current.setNext(step);
placed = true;
}
//move a space up the list
previous = current;
current = current.getNext();
}while(previous.getNext() != null || placed == false);
}
}
public int search(int num){
int nodeIndex = 0;
return 1; //Return index of num
}
public void delete (int num){
//delete num from the list
}
public void traverse(){
System.out.println(front.getNext());
System.out.println(front.getNext().getNext());
System.out.println(front.getNext().getNext().getNext());
System.out.println(front.getNext().getNext().getNext().getNext());
System.out.println(front.getNext().getNext().getNext().getNext().getNext());
}
public int getComparisons(){
return comparisons;
}
public class Node {
private Node next;
private int data;
public Node(){
next = null;
}
public Node(int data, Node next){
this.next = next;
this.data = data;
}
public Node getNext(){
return next;
}
public void setNext(Node nextNode){
next = nextNode;
}
public int getData(){
return data;
}
public void setData(int data){
this.data = data;
}
}
}
public class User {
public static void main(String[] args){
Class1 test = new Class1();
test.insert(1);
test.insert(3);
test.insert(5);
test.insert(2);
test.insert(4);
test.traverse();
}
}
我剛開始學習LinkedLists,而且我不確定的是什麼,我實現錯了。任何幫助將不勝感激。你真的只需要看看我的插入方法和內部節點類。
特別是因爲你已經檢查了前面是空之前,你就叫吧:) – realUser404 2014-12-03 21:37:15