next up previous contents
Next: The Protected Search Elements: Up: Overloaded I/O Methods: Previous: Is A Given Element

Insertion Agents:

The following code inserts a given element either before or after a chosen element in the list. These agents utilize the protected agent get_element_address (this returns the address of the DL_CELL which contains the chosen element).

    // ******************************************** //
    // insert a new element after a given element   //
    // ******************************************** //
 
void CHAR_DLLIST::insert_after(CHAR after_element,CHAR new_element)
{
  if(!(head==NULL) ){
    //use private search agents for class
    CHAR_DL_CELL *temp = get_after_element_address(after_element); 
    CHAR_DL_CELL *temp2 = get_element_address(after_element);
    if(temp==NULL && temp2!=NULL){
      //after_element is at the end of list.
      CHAR_DL_CELL *cell = new CHAR_DL_CELL("int");
      cell->element = new_element;
      cell->next = NULL;
      cell->previous = temp2;
      temp2->next = cell;
      end = cell;
      }
    if(temp!=NULL && temp2!=NULL){
      CHAR_DL_CELL *cell = new CHAR_DL_CELL("int");
      cell->element = new_element;
      cell->next = temp; 
      cell->previous = temp2; 
      temp2->next = cell; 
      temp->previous = cell;   
      }
    if(temp2==NULL){
      //after_element is not in the list, so do not insert
      cout << after_element << " is not in the list, so do not insert."
           << endl;
      }
    }
   else{
     cout << "List is empty, so do not insert." << endl;
     }
}

    // ******************************************** //
    // insert a new element before a given element  //
    // ******************************************** // 
void CHAR_DLLIST::insert_before(CHAR before_element,CHAR new_element)
{
  if(!(head==NULL) ){
    //use private search agents for class
    CHAR_DL_CELL *temp = get_before_element_address(before_element); 
    CHAR_DL_CELL *temp2 = get_element_address(before_element);
    
    if(temp==NULL && temp2!=NULL){
      //before_element is at head of list.
      CHAR_DL_CELL *cell = new CHAR_DL_CELL("int");
      cell->element = new_element;
      cell->next = temp2;
      temp2->previous = cell;
      head = cell;
      }
    if(temp!=NULL && temp2!=NULL){
      CHAR_DL_CELL *cell = new CHAR_DL_CELL("int");
      cell->element = new_element;
      cell->next = temp2;
      cell->previous = temp;
      temp->next = cell;
      temp2->previous = cell;  
      }
    if(temp2==NULL){
      //before_element is not in the list, so do not insert
      cout << before_element << " is not in the list, so do not insert."
           << endl;
      }
    }
   else{
     cout << "List is empty, so do not insert." << endl;
     }
}



 

Jim Peterson
1999-04-22