gpt4 book ai didi

c++ - 如何在给定索引后插入链表中的节点

转载 作者:行者123 更新时间:2023-11-28 04:16:15 25 4
gpt4 key购买 nike

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

我有一个 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;
};

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

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

最佳答案

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

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

关于c++ - 如何在给定索引后插入链表中的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56534785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com