Deleting linked list nodes recursivly

Hello all...

I was looking around the forum for other similar problems but I didn't find anything so I decided to post.

I am creating a Linear linked list in c++. I've written all the functions for it, but now I want to try and do them using recursion.

I managed to make functions for adding and displaying nodes on the list, but I am stuck on the function for removing nodes. First I want to try and write a function the removes the last item on the list. But for some reason my code isn't working properly.

Here is the code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void removeLastItem(node * &head)
{
    if(!head)
    {

        delete head;
        head = NULL;
        cout << "\nItem Deleted\n";
        return;
    }
    if(head)
    {
        cout << "\nAdvancing item...";
        removeLastItem(head->next);
        return;
    }
}


NODE - My structure name
NEXT - The pointer to next element.
HEAD - The first (head) pointer.

** The couts in the if statements are just for testing. In fact after I Run my program it does as it is supposed - enters the second if /b]case as many times as there are elements and then executes the first [b]if statement. But for some reason it does not delete the actual node.

Any help is much appreciated
Last edited on
your removeLastItem(...) doesn't do anything.
the if statement on line 3 doesn't make sense. You delete head if it's NULL.

I guess this is what you want:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void removeLastItem(node * &head)
{
    if(head)
    {
if(head->next)
{
        cout << "\nAdvancing item...";
        removeLastItem(head->next);
}
else
{
        delete head;
        head = NULL;
        cout << "\nItem Deleted\n";
}
    }
}
Wow...I am quite new to most of this, and I thought that when head is null it meant there is no next node, and by deleting head I am deleting the current node with its data.

Anyways thanks a lot... your example helped a lot. =)
Topic archived. No new replies allowed.