here is code for my assignment. I am getting:
Exception in thread "main" java.lang.NullPointerException
at SortedStringList.insert(SortedStringList.java:33)
at TestSortedStringList.main(TestSortedStringList.java:6)
Line 33 is the "while" loop in my insert.
Its supposed to be a double linked list of nodes w/string in each node, alphabetically arranged.
here is the code:
public class SortedStringList {
private static class Node {
public String value;
public Node next;
public Node previous;
public Node(String value, Node next, Node previous) {
this.value = value;
this.next = next;
this.previous = previous;
}
}
private Node first;
private Node last;
public SortedStringList() { //default constructor, make an empty list
this.first = null;
this.last = null;
}
public boolean insert(String s) {
Node current = first;
if (this.first == null && this.last == null) {
this.first = new Node (s, null, null);
}
if (this.member(s)) {return false;}
else while ((current.next != null) || (s.compareToIgnoreCase(current.value) > 0)) {
current = current.next;
}
if (current == last) {
Node newN = new Node (s, null, last);
this.last = newN;
current.next = newN;
}
if (current == first) {
Node newN = new Node (s, first, null);
first = newN;
current.previous = newN;
}
else {Node newN = new Node(s, current, current.previous);
current.previous.next = newN;
current.previous = newN;}
return true;
}
public boolean remove(String s) {
Node current = first;
if (this.first == null)
throw new RuntimeException ("remove called on an empty StringList");
if (!this.member(s)) {
return false;
}
else while (s.compareToIgnoreCase(current.value) == 0) {
current = current.next;
}
if (current.next == null) {
this.last = current;
current.next = null;}
if (current == this.first) {
this.first = current.next;
current.next.previous = null;
}
else { current.previous.next = current.next;
current.next.previous = current.previous;}
return true;
}
public boolean member(String s) {
if (first == null) {
return false;
}
Node current = first;
while (current != null && (s.compareToIgnoreCase(current.value) != 0)) {
current = current.next;}
if (current == null) {return false;}
else {return true;}
}
public String toString() {
String text = "";
Node current = first;
while (current != null) {
text += current.value + "\n";
current = current.next;
}
return text;
}
}