linked-list - 将一个节点插入到单个链表的第 n 个位置
问题描述
我正在尝试为单个链接列表创建一个 insert_at_position 函数,但是当我在列表末尾插入一个新节点时出现内存错误。
这是我的代码:
#include <iostream>
#include <memory>
#include <utility>
struct Node {
int data;
std::unique_ptr<Node> next = nullptr;
Node(const int& x, std::unique_ptr<Node>&& p = nullptr)
: data(x)
, next(std::move(p)) {}
};
std::unique_ptr<Node> head = nullptr;
Node* tail = nullptr;
void print() {
auto temp = head.get();
while (temp) {
std::cout << temp->data << " ";
temp = temp->next.get();
}
std::cout << "\n";
}
void push_back(const int& theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
if (!head) {
head = std::move(newNode);
tail = head.get();
}
else {
tail->next = std::move(newNode);
tail = tail->next.get();
}
}
void push_front(const int& theData) {
std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
newNode->next = std::move(head);
head = std::move(newNode);
if (!tail) {
tail = head.get();
}
}
void insert_at_position(int pos, const int& theData) {
if (pos == 1) {
push_front(theData);
return;
}
auto newNode = std::make_unique<Node>(theData);
auto current = head.get();
for (int i = 1; i < pos; i++) {
current = current->next.get();
}
if (current != nullptr) {
newNode->next = std::move(current->next);
current->next = std::move(newNode);
}
else {
push_back(theData);
}
}
void pop_front() {
head = std::move(head->next);
}
void pop_back() {
if (!head) return;
auto current = head.get();
Node* previous = nullptr;
if (current->next != nullptr) {
previous = current;
current = current->next.get();
}
if (previous != nullptr) {
previous->next = nullptr;
}
else {
head = nullptr;
}
tail = previous;
previous->next = nullptr;
}
void erase(int pos, const int& theData) {
}
int main() {
push_back(2);
push_back(4);
push_back(6);
print();
push_front(1);
print();
pop_front();
print();
/*pop_back();
print();*/
insert_at_position(1, 1);
print();
insert_at_position(8, 4);
print();
//insert_at_position(3, 2);
//print();
//
std::cin.get();
}
错误发生在这一点上:insert_at_position(8, 4);
我的逻辑是在最后一个 if 语句之后处理我插入到列表中间的某个随机位置的情况,我将在最后,因此会调用 push_back 函数。
解决方案
insert_at_position(8, 4)
尝试在位置 8 处插入到一个更短的列表中。内部的循环对此没有任何保护,并且在到达列表末尾时很高兴地取消引用空指针。
推荐阅读
- java - Java“Foo f = new Foo()”中的对象初始化与在 C 中使用 malloc 指针本质上相同吗?
- python - 我想取一个文本文件中所有数字的平均值
- dataset - 如何使用 TF 2.0 从海量二进制数据中生成训练数据集?
- java - 如何判断一个类是否存在于项目中
- doxygen - 我可以生成将出现在 doxygen 报告中的常规文档吗?
- mysql - 为什么我会收到错误 1054:某些输入的字段列表中的未知列?
- php - 获取邮件正文的数据:phpmailer
- angular - Angular 7:使用异步管道过滤多个键的搜索结果
- azure-active-directory - 在 Microsoft OpenId Connect / Azure AD 中自定义登录页面
- python - Python Beautiful Soup 使用类解析表