Source of 12.24.java


  1: // @author Frank M. Carrano, Timothy M. Henry
  2: // @version 5.0
  3: public T remove(int givenPosition)
  4: {
  5:    T result = null;                           // Return value
  6:    if ((givenPosition >= 1) && (givenPosition <= numberOfEntries))
  7:    {
  8:    // Assertion: !isEmpty()
  9:       if (givenPosition == 1)                 // Case 1: Remove first entry
 10:       {
 11:          result = firstNode.getData();        // Save entry to be removed
 12:          firstNode = firstNode.getNextNode();
 13:          if (numberOfEntries == 1)
 14:             lastNode = null;                  // Solitary entry was removed
 15:       }
 16:       else                                    // Case 2: Not first entry
 17:       {
 18:          Node nodeBefore = getNodeAt(givenPosition - 1);
 19:          Node nodeToRemove = nodeBefore.getNextNode();
 20:          Node nodeAfter = nodeToRemove.getNextNode();
 21:          nodeBefore.setNextNode(nodeAfter);
 22:          result = nodeToRemove.getData();
 23:          if (givenPosition == numberOfEntries)
 24:             lastNode = nodeBefore;            // Last node was removed
 25:       } // end if
 26:       numberOfEntries--;
 27:    }
 28:    else
 29:       throw new IndexOutOfBoundsException(
 30:                 "Illegal position given to remove operation.");

 32:    return result;                             // Return removed entry
 33: } // end remove