Functions using linkedlists not working as intended

I've just started using linkedlists and have run into a couple problems. I'm trying to write a practice program that lets the user add an element to the end of a list, print out the list, get the size of the list, remove an element from the end of the list and delete the list. The issue I am getting is that when I am trying to add an element to the list, it does not actually add the element.

Here is my code:x
Last edited on
?
you have a singly linked list and you want to insert at end - your current method seems unnecessarily complicated, it can be done much more simply like here: http://stackoverflow.com/questions/20125477/linked-list-insert-at-the-end-c
also, what's going on with these functions ... why are they all (seemingly) recursive with different signatures?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    void addAtEnd(string value)
        {
            addAtEnd(mHead, value);
        }
 
        void deleteList()
        {
            deleteList(mHead);
        }
 
        void displayList()
        {
            displayList(mHead);
        }
 
        void removeAtEnd()
        {
            removeAtEnd(mHead);
        }
 
They call the corresponding member function.
The problem is

void helperFunction(int choice, BookList List)

You pass the list as a copy which is discarded after the function is done.

Pass ist as a reference:

void helperFunction(int choice, BookList &List) // Note: &

In a singly linked list, it's fast to add/remove items from the front of the list, but terribly slow to do it at the end. Look at forward_list<> and you'll see that it doesn't even have a push_back() method, most likely because the designers didn't want you to accidentally use this inefficient function without realizing the consequences. So if you want to practice, I encourage you to write code to add/remove items from the front of the list.

Since addAtEnd() sets mHead() if needed, I'd change the return type to void. There's no need to return anything.

~BookList() should just call deleteList()

If removeAtEnd() is called with an empty list then line 149 will dereference a null pointer.

If removeAtEnd() is called with a list containing 1 item the mHead should be updated.

RemoveFromFront() is fragile because it only really works when called as mHead = removeFromFront(mHead);
Topic archived. No new replies allowed.