New programmer here, I am trying to understand and break down this code below for a remove method, sorted linked list. I have added comments below for what my understand is and what i do not understand. can someone shed some light on the things which are unclear?
thanks in advance.
/* 1 */ public void remove(E e) throws NotFoundException{
/* 2 */ Node<E> p; //declares node p
/* 3 */ // chunk below determines where to start traversing based on element value. should traverse from head if new element < pos value
/* 4 */ if(pos == head || pos.compareTo(e) >= 0 ){ //I do not understand 2nd equality..why?
/* 5 */ p = head; //traverse list from head
/* 6 */ }else{
/* 7 */ //traverse list from pos
/* 8 */ p = pos;
/* 9 */ }
/* 10 */ for( ;p.next!=null && p.next.compareTo(e)<0; p = p.next); //nothing to initialize?
/* 11 */ //e not found in the list
/* 12 */ if(p.next == null || p.next.compareTo(e) > 0){
/* 13 */ throw new NotFoundException();
/* 14 */ }
/* 15 */ if(p.next == pos){
/* 16 */ //if node to be deleted is pos, update pos to head
/* 17 */ pos = head;
/* 18 */ }
/* 19 */ p.next = p.next.next; //delete node
/* 20 */ }
First, here is a documentation for compareTo
The 2nd equality checks if pos points to a node that comes after “e”. if it’s true then u must traverse the list from its head because e comes before pos. Else, e comes after pos so you can traverse the list from pos. This is true because the list is sorted.
Here you start scanning the list from the position that was chosen and if you get to a node that is null (the end of the list) or a node that is greater than “e” then you know that “e” is not found in the list (because the list is sorted), so you throw an exception
Line 10: you don’t have to initialize anything here because you already initialized p above.