So I'm building my own doubly linked list class (not for homework, just trying to build my own libraries for later use), and I'm having some difficulties implementing a removeAll method. Here is the relevant code (if you need more, let me know):
//ptr is a pointer node that moves through the list
//removes all nodes with type data
public void removeAll(T data) {
while (findNode(data) != null) {
deleteNode(findNode(data));
} // end of while
} // end of removeAll method
//deletes single node
private void deleteNode(Node<T> del) {
// del is head node
if (del.prevNode == null)
removeFirst();
// del is tail node
else if (del.nextNode == null)
removeLast();
else {
del.nextNode.prevNode = del.prevNode;
del.prevNode.nextNode = del.nextNode;
size--;
} // end of if-else
} // end of deleteNode method
//returns node that matches criteria
private Node<T> findNode(T data) {
ptr = head; // reset pointer
while(ptr != null) {
if(ptr.data == data)
break;
else {
ptr = ptr.nextNode;
} // end of if-else
} // end of while
return ptr;
} // end of findNode method
Output trying to remove 713 (I used integers for simplicity):
[ 9 -6 -6 -6 -6 2 3 713 ] // this is just to show all elements in linked list
------------- // divider
[ 9 -6 -6 -6 -6 2 3 713 ] // after trying to remove 713
What I think is most interesting is that if I try to remove all the -6's, the removeAll method works.
[ -6 9 -6 -6 -6 2 3 713 -6 ] //added -6 to beginning and end
-------------
[ 9 2 3 713 ] //all -6's gone
It's as if 9 and 713 are just random cases where the methods don't work. I think the problem lies within the findNode and deleteNode methods. Testing the removeFirst and removeLast methods showed that they work flawlessly and give correct outputs. Any help/guidance is greatly appreciated, I've been struggling with this for close to 6 hours.