c++ - 如何在给定索引之后在链表中插入节点
问题描述
我试图在链表中的给定索引处和最后插入一个节点,但我不理解语法甚至概念上我在做什么。
我对这两个问题都有一个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>>'
解决方案
您的两个功能都实现了错误。它们需要看起来更像这样(假设正在使用单链表):
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;
}
}
推荐阅读
- ruby-on-rails - 如何有条件地应用 Rails 中的 where 子句?
- .htaccess - 将旧站点重定向到新问题(Prestashop)
- javascript - 用于更改主题的 React Native Context
- python - 为什么 Pygame 文本打印没有完全覆盖最后一个文本打印,并且在文本周围留下奇怪的光环?
- sql - Postgres:jsonb对象的多个条件
- javascript - 单击特定的 h3 标签后如何更改视频的来源?
- amazon-web-services - AWS HTTP API 网关:句柄 /
- android - 使用 Java 11 运行 sonarqube-gradle-plugin:3.3 时出错
- flutter - 按钮不出现
- jquery - 图例分页器在窗口调整大小时错误显示