Linked List Delete Function

I have a linked list of students. Each node in my list has a pointer to a student object which contains the data for that student. I wrote a function that deletes every student with a specified name.

This is my first time ever making a linked list, and, although I got the function working, I wonder if there is a more efficient way to do it (my code seems a little too convoluted).

You guys definitely have a lot more experience than I do with this, and I was wondering if you could look over my code and see if there are any obvious ways to make it more efficient.

Thanks in advance.

Here's my code: (code removed, problem solved)

Last edited on
I probably won't help you with your function (seems like there's a class called Node which I don't know of), but why not try using something that's already thoroughly tested and secure?

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
#include <iostream>
#include <string>
#include <list>
#include <algorithm>


int main()
{
    std::list<std::string> students
    {
        "Clara",
        "John",
        "ABCD",
        "Curry",
        "Strawberry",
        "SugarSpice"
    };

    std::string who = "ABCD";

    std::list<std::string>::iterator it = std::remove_if(students.begin(),
                                                        students.end(),
                                                        [&who](const std::string &name)
                                                        {
                                                            return name == who;
                                                        });
    students.erase(it, students.end());
    for (auto &x : students)
        std::cout << x << std::endl;

    return 0;
}


std::remove_if on a list moves all items to be deleted to the back of the container, and returns an iterator to the first element that's supposed to be deleted.
From that element (it), we traverse towards students.end(), deleting everything in between.
Ok, thanks for help!
Topic archived. No new replies allowed.