I have a practice problem from a book that I cant figure out. I wrote code that creates a link list up to ten nodes, but when i try to delete a node using recursive function it doesnt work. I tried to delete the node with the value of 4 (I typed 1,2,3,4,5,6,7,8,9,10) but it wont delete it, in fact it crashes.
Been stuck on this problem for nearly an hour. lines 31-46 is the delete function.
#include <iostream>
usingnamespace std;
struct Link_List
{
int value;
Link_List *next_list;
};
//recursive function that creats link list up to 10 nodes
Link_List *Create_Link_List(Link_List *arg, int range)
{
if (range > 0)
{
Link_List *p_new_list = new Link_List;//allocated memory for new node
cout << "Enter a value for your list." << endl;
cin >> p_new_list->value;// enter value for variable value in structure
p_new_list->next_list = arg;// make p_new_list point to previous node
arg = p_new_list;// make arg point to node just created
return Create_Link_List(arg,range - 1);// recurse function till range reaches 0
}
}
//recurive function that finds the node to delete, which holds a value of 4
Link_List *Delete_List(Link_List *arg, int value_to_find)
{
if (arg == NULL)
{
return NULL;// return NULL if at end of list
}
elseif (arg->value == value_to_find)
{
arg = arg->next_list; // if value is found, point to next node
return Delete_List(arg,value_to_find);// recurse again to get rest of nodes
}
else
{
return Delete_List(arg->next_list,value_to_find);// value not found yet, keep searching
}
}
int main()
{
Link_List *New_List = NULL;// sets head of list to node
New_List = Create_Link_List(New_List,10);// creates 10 nodes for list, New_List points to head of list
Link_List *Transverse_List = New_List;// variable to transverse list without ruining original data
// loop that transverses original list
for (int i = 0; i < 10; ++i)
{
cout << Transverse_List->value << endl;
Transverse_List = Transverse_List->next_list;
}
// give space so we can see the new list below which displays the node that was deleted
cout << endl;
cout << endl;
cout << endl;
New_List = Delete_List(New_List, 4);//deletes the node with the value of 4
Transverse_List = New_List; // variable to transverse list without ruining the original data
//loop that transverses the new list with the node deleted
for (int i = 0; i < 9; ++i)
{
cout << Transverse_List->value << endl;
Transverse_List = Transverse_List->next_list;
}
}