The following code inserts a given element either before or after a chosen element in the list. These agents utilize the protected agents get_before_element_address (this returns the address of the SL_CELL which points to the SL_CELL containing the chosen element); get_element_address (this returns the address of the SL_CELL containing the chosen element); and get_after_element_address (this returns the address of the SL_CELL which is pointed to by the SL_CELL containing the chosen element).
// ******************************************** //
// insert a new element after a given element //
// ******************************************** //
void CHAR_SLLIST::insert_after(CHAR after_element,CHAR new_element)
{
if(!(head==NULL) ){
//use private search agents for class
CHAR_SL_CELL *temp = get_after_element_address(after_element);
CHAR_SL_CELL *temp2 = get_element_address(after_element);
if(temp==NULL && temp2!=NULL){
//after_element is at the end of list.
CHAR_SL_CELL *cell = new CHAR_SL_CELL("int");
cell->element = new_element;
cell->next = NULL;
temp2->next = cell;
}
if(temp!=NULL && temp2!=NULL){
//temp is address of cell after cell with after_element
//temp2 is address of cell containing after_element
CHAR_SL_CELL *cell = new CHAR_SL_CELL("int");
cell->element = new_element;
cell->next = temp; //cell->next points to before_element cell
temp2->next = cell; //temp points to cell containing new_element
}
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_SLLIST::insert_before(CHAR before_element,CHAR new_element)
{
if(!(head==NULL) ){
//use private search agents for class
CHAR_SL_CELL *temp = get_before_element_address(before_element);
CHAR_SL_CELL *temp2 = get_element_address(before_element);
if(temp==NULL && temp2!=NULL){
//before_element is at head of list.
CHAR_SL_CELL *cell = new CHAR_SL_CELL("int");
cell->element = new_element;
cell->next = head;
head = cell;
}
if(temp!=NULL && temp2!=NULL){
//temp is address of cell prior to cell with before_element
//temp2 is address of cell containing before_element
CHAR_SL_CELL *cell = new CHAR_SL_CELL("int");
cell->element = new_element;
cell->next = temp2; //cell->next points to before_element cell
temp->next = cell; //temp points to cell containing new_element
}
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;
}
}