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

Answer:

See below.


Insert into an Empty List

Here are four cases that cover all situations:

  1. Inserting into an empty list
  2. Inserting at the head of the list (because the new value is less than or equal to the current head)
  3. Inserting at the end of the list (because the new value is greater than the current last node)
  4. Inserting into the middle of the list (because the new value fits between two existing nodes)

Here is a skeleton of the class so far:

public class OrderedLinkedList
{
   private Node headPtr = null;
  
  // The constructor creates an empty list
  public OrderedLinkedList()
  {
    headPtr = null;
  }
 
  // various methods left out

  // Insert one Node containing data  
  // into the list in ascending order.
  // Duplicates are allowed.
  public void insertInOrder( int data )
  {
  
    // Create the node to be inserted
    Node newNode = new Node( data );
    newNode.setNext( null );
    
    // CASE 1: insert into an empty list
    if (    )
    {
         
        return;
    }
    
    // CASE 2:
      
    // CASE 3:
    
    // CASE 4:
  }
}

For all cases a new Node containing the data is created. Then each case is handled separately.

The first case is inserting into an empty list.

Insert First

QUESTION 5:

Complete the first case by filling in the blanks.

(Hint: ) Inserting into an empty ordered list is the same as inserting into an empty unordered list.


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