Question

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 */ }
Was it helpful?

Solution

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. }

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.

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. }

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.

OTHER TIPS

Line 4: it is a sorted list, so if the element you want to remove is greater or equal to what pos points to, it is fine to start moving from pos (rather than from the head of the list) - (in case you don't know, a.compareTo(b) < 0 if a < b, 0 if a == b and > 0 if a < b)

Line 10: move through the list while p.next is lower than what you are looking for (and not null) - once finished, either you are at the node you are looking for or it throws NotFoundException()

Anything else not clear?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top