Simple
Simple

Reputation: 11

How to insert a node in a linked list after a given index

I am trying to insert a node at a both given index in a linked list and just at the end, but I don't understand the syntax or even conceptually what I am doing.

I have an insertTail function and an insertAfter function for both of these problems, but I'm not sure I am implementing them correctly.

void insertTail(T value) {
        if (head == NULL) {
            insertHead(value);
        }
        else {
            T tailNode = Node(value);
            Node* tempPtr = head;
            while (tempPtr != NULL) {
                tempPtr = tempPtr->next;
            }
            next = tailNode->data;
        }

    };

void insertAfter(T value, T insertionNode) {
        Node* tempPtr = head;
        while (tempPtr->data != insertionNode) {
            tempPtr = tempPtr->next;
        }
        Node* afterNode = new Node(value);
        afterNode->next = tempPtr->next;
        tempPtr->next = afterNode;
    };

My code won't even compile with what I have currently. It gives an error for the first line in the else statement in the insertTail function that reads

'initializing': cannot convert from 'LinkedList<std::string>::Node' to 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>'

Upvotes: 0

Views: 601

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596352

Both of your functions are implemented all wrong. They need to look more like this instead (assuming a single-linked list is being used):

void insertTail(T value) {
    if (!head) {
        insertHead(value);
    }
    else {
        Node* tailNode = head;
        while (tailNode->next) {
            tailNode = tailNode->next;
        }
        tailNode->next = new Node(value);
    }
}

void insertAfter(T value, Node *insertionNode) {
    if (!insertionNode) {
        insertTail(value);
    }
    else {
        Node* newNode = new Node(value);
        newNode->next = insertionNode->next;
        insertionNode->next = newNode;
    }
}

Upvotes: 1

Related Questions