首页 > 解决方案 > 将一个节点插入到单个链表的第 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 函数。

标签: linked-listc++14

解决方案


insert_at_position(8, 4)尝试在位置 8 处插入到一个更短的列表中。内部的循环对此没有任何保护,并且在到达列表末尾时很高兴地取消引用空指针。


推荐阅读