1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
struct sll_node//singly linked list node
{
string date;
sll_node *next;
};
sll_node* r_remove(string node_data, sll_node** front, sll_node* prev_)//returns updated list (so front ptr) or NULL (reached end of list and not found)
{
sll_node* prev = prev_;
sll_node* cur = *front;//pts to what front ptr points to initially
if ( prev == NULL && cur == NULL ) return NULL;//Base case:if empty list
else if ( cur->data == node_data && prev == NULL )//base case: else if node to remove is first node, update front to point to next node in line
{
*front = (*front)->next;
delete cur; cur = NULL;
return *front;
}
// if we find node to remove somewhere else, return updated list (=>return ptr front (front pts to list)
//node could either be first node or somewhere else in list (need to update relink w/ prev and delete cur)
else if ( cur->data == node_data && prev != NULL )
{
prev->next = cur->next;
delete cur; cur = NULL;
return *front;
}
//if EOL (reached end of list), => node not on list since we always compare w/ cur ptr and once cur pts to NULL, of course no more items to compare with!
else if ( cur == NULL && prev != NULL ) return NULL;
else return r_remove(node_data, &(*front)->next, *front);//keep traversing
}
int main()
{
sll_node *front = NULL;
sll_node *end = NULL;
insert_at_end("j", &front, &end);//I have this working
insert_at_end("d", &front, &end);
insert_at_front("h", &front);//I have this function working
insert_at_front("g", &front);
if ( !r_remove("jad", &front, NULL) )
cout << "No node found to be removed" << endl;
else
cout << "Removed" << endl;
return 0;
}
|