How to delete user inputted nodes in a linked list C++

Viewed 38

I'm currently working on some of my code. I'm trying to learn how the "List Class" from the STL library works under the hood. I can't seem to quite understand the process of removing a node from a list made by the user. Is there any information that is accessible that would better help me wrap my head around this problem.

#include <iostream>
#include <string>


using namespace std;

class Node {
public:
    string todos;
    Node* next;


    Node(string todos) {

        this->todos = todos;
        next = NULL;
    }

};

void print_list(Node* head) {

    Node* temp = head;
    while (temp != NULL) {
        cout << temp->todos << " ";
        temp = temp->next;
    }
}

Node* takeinput() {
    string var;
    int num;
    

    Node* head = NULL;
    Node* tail = NULL;

    cout << "Please enter 5 Todo tasks. " << endl;

    cout << endl;

    cout << "If you would like to exit this prompt please enter 'End' " << endl;

    cout << "If you would like to enter an item onto the list please press 1 " << endl;

    cout << endl;


    cin >> num;

    while (var != "End") {
        
        if (num == 1) {
            Node* newNode = new Node(var);
            
            if (head == NULL) { 
                head = newNode;
                tail = newNode;

            }

            else {
                tail->next = newNode;
                tail = tail->next;
            }
        }
        cin >> var;
        if (num == 2) {

        }
    }
    return head;
}

int main()
{
    string hello;

    Node* head = takeinput();
    

    print_list(head);



} 
1 Answers

I'm trying to learn how the "List Class" from the STL library works under the hood.

std::list is a doubly linked list with user specified type for node data.

For Visual Studio, it is a circular linked list with a dummy node, where dummy.next is a pointer to the first node and dummy.prev is a pointer to the last node, and where first_node.prev and last_node.next point to the dummy node. There is a list size and optional user defined allocator (for nodes). There is support for iterators with operator overloading. std::list::end() returns an iterator to the dummy node (note that iterators can't be null). std::list::splice() allows nodes to be moved within a list or from one list to another.

std::list::sort() should be a bottom up merge sort for linked lists, but starting with Visual Studio 2015, it was changed to a less efficient top down merge sort for linked list when it was switched to be iterator based. If interested, link to example bottom up version:

`std::list<>::sort()` - why the sudden switch to top-down strategy?

The source code for std::list is ~2000 lines. I recommend starting off with just basic double linked list code.

Related