将节点插入单个链表的第n个位置

时间:2018-09-23 19:47:37

标签: linked-list c++14

我正在尝试为单个链接列表创建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函数。

1 个答案:

答案 0 :(得分:1)

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