There are four cases:
As an added twist the value to be deleted might or might not be in the list.
Here the method. Look at the pictures on the previous page and select the correct conditional expression for each blank.
Keep in mind short-circuit evaluation.
public class OrderedLinkedList { private Node headPtr = null; . . . . // Delete the first node that contains value. // if a node was deleted, return true // if the value was not found, return false // public boolean deleteValue(int value) { // CASE I: Empty list if ( ) return false; // CASE II: Delete first node // value is in first node, unlink it, return true if ( ) { headPtr = headPtr.getNext(); return true; } // CASE III and CASE IV: delete middle or last node. // Search for a node that contains value. // Might be last one. Node current = headPtr; Node next = headPtr.getNext(); while ( ) { current = next; // advance both next = next.getNext(); // pointers } // if value is found, give current node // the pointer in next node, which might be null if ( ) { current.setNext( next.getNext() ); return true; } // value not in the list: return false return false; } . . . }
Select the right condition for each if
or while
statement.