The concept behind the code is to delete elements in a list that are greater than the element before it. In this case my nodes have an int data and are comparable through that. (The class these are in extends Comparable<>
The issue is when I get a nullpointexception when this code runs with the linked list:
[2,5,4,3,7,6,4,2,3,4,5]
The expected list that should be gotten is
[2,2]
Because (5 > 2) removes 5 then (4 > 2) removes 4 then (3 > 2) removes 3 ... and so on until it hits the end with a nullpointerexception.
Another example would be for the list
[3,1,-2,3,6,-1,3,2,1]
The list should end up being
[3,1,-2]
The debug code in there is to show which elements got removed.
The getter methods are basics and work fine.
public void deleteIncrementing() {
T largest = null;
while(head.getNext() != null || head != null) {
Node<T> temp = head.getNext();
while(temp.getValue().compareTo(head.getValue()) > 0){
largest = temp.getValue();
remove(largest);
System.out.println(largest); // debug
if(temp.getNext() == null){
break;
}
temp = head.getNext();
}
head = temp;
}
}
DERIVED FROM SUGGESTED PSEUDO-CODE:
Node<T> current = head;
Node<T> previous = null;
while(current != null) {
if (previous != null){
if (current.getValue().compareTo(previous.getValue()) > 0){
//System.out.println(current.getValue().toString());
remove(current.getValue());
}
if (current.getValue().compareTo(previous.getValue()) < 0){
//System.out.println(previous.getPrevious().getValue().toString());
//System.out.println(current.getValue().toString());
remove(previous.getValue());
}
}
previous = current;
current = current.getNext();
}
Which still isn't correct because it doesn't take in account the first to last element and keep the final one attached... any reasons?