go to previous page   go to home page   go to next page highlighting

Answer:

There are four cases:

  1. Delete from empty List
  2. Delete first node
  3. Delete a middle node
  4. Delete last node

As an added twist the value to be deleted might or might not be in the list.


Four Cases

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

QUESTION 16:

Select the right condition for each if or while statement.


go to previous page   go to home page   go to next page