2016-10-22 2 views
0

Я занимаюсь созданием двусвязного списка, содержащего строковое значение.Метод поиска со связанными списками

В методе находят, у меня есть NullPointer Exception

вот мой код.

package LinkedList; 



package LinkedList; 

public class LinkedList { 

// 노드 클래스 
class Node { 
    String value; 
    Node prev; 
    Node next; 

    Node(String v, Node p, Node s) { 

     value = v; 
     prev = p; 
     next = s; 
    } 

    public String getValue() { 
     return value; 
    } 

    public Node getPrev() { 
     return prev; 
    } 

    public Node getNext() { 
     return next; 
    } 

    public void setPrev(Node p) { 
     prev = p; 
    } 

    public void setNext(Node n) { 
     next = n; 
    } 

} 

Node head; 
Node tail; 
int size = 0; 

public LinkedList() { 
    head = new Node(null, null, null); 
    tail = new Node(null, head, null); 
    head.setNext(tail); 
} 

public int size() { 
    return size; 
} 

public boolean isEmpty() { 
    return size == 0; 
} 

public String first() { 
    if (isEmpty()) { 
     return null; 
    } 
    return head.getNext().getValue(); 
} 

public String last() { 
    if (isEmpty()) { 
     return null; 
    } 
    return tail.getPrev().getValue(); 
} 

public void addFirst(String value) { 
    addBetween(value, head, head.getNext()); 
} 

public void addLast(String value) { 
    addBetween(value, tail.getPrev(), tail); 
} 

public void addBetween(String v, Node p, Node s) { 
    Node newNode = new Node(v, p, s); 
    p.setNext(newNode); 
    s.setPrev(newNode); 
    size++; 
} 

public String remove(Node node) { 
    Node p = node.getPrev(); 
    Node s = node.getNext(); 
    p.setNext(s); 
    s.setPrev(p); 
    size--; 
    return node.getValue(); 
} 

public String removeFirst() { 
    if (isEmpty()) { 
     return null; 
    } 
    return remove(head.getNext()); 
} 

public String removeLast() { 
    if (isEmpty()) { 
     return null; 
    } 
    return remove(tail.getPrev()); 
} 

public void insert(String value) { 
    Node current = head; 
    // first 
    if (isEmpty()) { 
     addFirst(value); 
    } else { 
     // check 
     while (current.getNext() != tail || current.getValue().compareTo(value) > 0) { 
      current = current.getNext(); 
     } 
     // last 
     if (current.getNext() == tail) { 
      addLast(value); 
     } else // between 
     { 
      addBetween(value, current.getNext(), current); 
     } 

    } 
} 

/* !!!!!!!!!!!!!! ERORR !!!!!!!!!!!! */ 
public void find(String value) { 

    Node current = head.getNext(); 

    while ((current != null) || !(current.getValue().equals(value))) 

     current = current.getNext(); 

    if (current.getValue().equals(value)) { 
     System.out.println("found " + value); 
    } else { 
     System.out.println("Not found " + value); 
    } 

} 

// • Traverse the list forwards and print 
// 순회 
public void fowardTraverse() { 
    Node current = head.getNext(); 

    System.out.print(current.getValue()); 

    while (current.getNext() != tail) { 
     current = current.getNext(); 
     System.out.print(" -> " + current.getValue()); 
    } 

} 

// • Traverse the list backwards and print 
// 뒤로 순회 
public void backwardTraverse() { 

    Node current = tail.getPrev(); 

    System.out.print(current.getValue()); 

    while (current.getPrev() != head) { 
     current = current.getPrev(); 
     System.out.print(" -> " + current.getValue()); 
    } 

} 

// • Delete a node from the list 
    // 지우기 
    public String delete(String value) { 
     return value; 
    } 

    // • Delete/destroy the list 
    // 파괴하기 
    public void destroy() { 

    } 

    public static void main(String[] args) { 
     // TODO Auto-generated method stubs 

     LinkedList a = new LinkedList(); 
     a.insert("a"); 
     a.insert("b"); 
     a.insert("c"); 
     a.insert("d"); 
     a.insert("e"); 
     a.insert("f"); 
     a.insert("g"); 
     a.insert("h"); 
     a.insert("i"); 
     // a.fowardTraverse(); 
     a.find("a"); 

    } 

Я не понимаю, почему я получаю nullpointException на линии,

Это, предполагают, чтобы поместить узел содержит.

+0

Проверьте, 'current.getValue () 'is not null – Khaled

ответ

0

Убедитесь, что вы проверить не-NULL перед тем разыменования:

Node current = head.getNext(); 

и

if (current.getValue().equals(value)) { 

быть заменен

Node current; 
if(head != NULL) current = head.getNext(); 

и

if (current != NULL && current.getValue().equals(value)) { 
0

Потому что ваша голова пуста ... (не каламбур) перед тем структурой calling..your AddFirst: головы = [NULL, NULL, хвост], хвост = [пустой, голова, пустой]; вы отправляете («a», head, tail) и сохраняете его в новом узле, создавая его как: head = [null, null, newNode] ==> newNode ["a", head, tail] ==> хвост [нуль, newNode, нуль]

Так поиск будет сравнивать нуль а (в находке) дает вам ошибку ..... --- Edit 1: @JanghyupLee, My Bad, Didn «т сделать более близкий взгляд на метод находят ... однако, я обнаружил, что в состоянии„если“вы используете условие

current != null || ...... 

После первой линии, (ток = head.next) .. ток становится не null ..

, вызывающий условие при игнорировании правой части '||' (Короткое замыкание) до тока имеет значение нуля ...

Когда ток становится нулевым, тогда он идет к следующему оператору, чтобы проверить для value..causing исключения нулевого указателя

+0

Итак, я думаю, голова имеет значение null, но я сделал head.next в потоке. если я ошибаюсь, не могли бы вы объяснить более подробно? –

Смежные вопросы