简体   繁体   中英

Sorted Linked List gives NullPointerException

I am creating a Sorted Linked List where integers are stored in ascending order. I am having a trouble with add() method. It works when I add first node but when I try to add another one it gives me NullPointerException

Here is my code for Node class:

public class Node {
  int value;
  Node next;

  public Node() {
  }

  public Node(int c) {
    this.value = c;
  }

  public boolean hasNext() {
    if (next == null) {
       return false;
    } else {
       return true;
  }


}

And this is part of my SortedList class:

  public class SortedList {

    Node head;
    public int listCount;


    public SortedList() {
      listCount = 0;
      this.head=null;
    }

    public void add(int num) {
      Node newNode = new Node(num);
      Node temp = head;

      if (head == null) {
        head = newNode;
        listCount++;
        System.out.println("Node with data "+num+" was added.");
       } else {
        while (temp.value <= num) {    //the compiler shows NullPointerException here in this line 
            temp = temp.next;
        }
          if (temp.next==null) {
            temp.next=newNode;
            listCount++;
            System.out.println("Node with data "+num+" was added.");
        } else {
            newNode.next=temp.next.next;
            temp.next=newNode;
            listCount++;
            System.out.println("Node with data "+num+" was added.");
        }


    }

}

It says that the java.lang.NullPointerException is at "while (temp.value <= num)" line

Consider these lines of your program:

while (temp.value <= num) { 
    temp = temp.next;
}

Each time through the loop, temp is accessed in order to retrieve its value , and if that value is less than or equal to num , you move on to the next node.

However, there's nothing in this code that handles what happens when you hit the "end" of your sorted list (and therefore temp.next is null ). When that happens, null is assigned to temp , and then the loop condition is checked again and temp.value throws a NullPointerException.

Exactly how you solve this is somewhat a matter of preference. Probably you want to stop when temp holds the tail of the list. So perhaps you could change the loop condition to

while (temp.value <= num && temp.next != null)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM