2017-09-12 85 views
1

所以我有這個基本的泛型植入通用雙向鏈表。我已經創建了一個插入方法,它將根據順序添加一個節點。通用雙鏈表實現

public class DoublyLL <T extends Comparable<T>> { 
DNode<T> head; 
DNode<T> tail; 

public void insertInOrder(T item) { //To create an "ordered" linked list 
    DNode <T> n = new DNode<>(); 

    if (head == null) { 
     head = n; 
     n.data = item; 
    } 
    else { 
     DNode<T> temp = head; 
     while (temp != null && n.data.compareTo(temp.data) > 0) { // line 18 
      temp = temp.next; 
     } 
     if (temp == head) { //inserting node in first 
      head.prev = n; 
      n.next = head; 
      head = n; 
      n.data = item; 
     } 
     else if (temp == null) { // inserting at last 
      tail.next = n; 
      n.prev = tail; 
      tail = n; 
      n.data = item; 
     } 

     else { //inserting in middle 
      n.prev = temp.prev; 
      n.next = temp; 
      temp.prev.next = n; 
      temp.prev = n; 
      n.data = item; 
     } 
    } 


    } 

@Override 
public String toString() { 
    DNode temp = head; 
    String str = ""; 
    while (temp != null) { 
     str += temp.data + " "; 
     temp = temp.next; 
    } 
    return str; 
} 



public static void main(String[] args) { 
    DoublyLL<Integer> list = new DoublyLL<>(); 
    list.insertInOrder(2); 
    list.insertInOrder(222); //line 62 
    list.insertInOrder(22222); 
    System.out.println(list); 

} 
} 

class DNode<T> { 
T data; 
DNode prev; 
DNode next; 
} 

然而,當我在第18行運行此我得到的NullPointerException和62我能做些什麼來擺脫這使有序列表一樣,「2,22,2222?

+1

這個異常是否告訴你*它發生在哪裏?請複製粘貼(作爲文本)異常的* full *輸出到問題主體中。 –

回答

0

很難說什麼是沒有堆棧跟蹤的問題,但它看起來像,而不是

if (head == null) { 
    head = n; 
    n.data = item; 
} 

你應該有

if (head == null) { 
    head = n; 
    tail = n; 
    n.data = item; 
} 

否則你的tail保持爲空。