首页 > 解决方案 > 如何在给定索引之后在链表中插入节点

问题描述

我试图在链表中的给定索引处和最后插入一个节点,但我不理解语法甚至概念上我在做什么。

我对这两个问题都有一个insertTail函数和一个insertAfter函数,但我不确定我是否正确实现了它们。

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;
    };

我的代码甚至不能用我目前的代码编译。它在读取else的函数中的语句的第一行给出错误insertTail

'正在初始化':无法从 'LinkedList<std::string>::Node' 转换为 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>'

标签: c++

解决方案


您的两个功能都实现了错误。它们需要看起来更像这样(假设正在使用单链表):

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;
    }
}

推荐阅读