双链表,插入位置

时间:2018-09-24 16:42:29

标签: c++ linked-list c++14

我正在为即将进行的一些面试学习,并且我正在练习编写一些常见的数据结构以供练习。到目前为止,除了insert_at_position之外,我所有的功能都可以正常工作。当我尝试插入值1的开始节点时,我得到了1的两个值,我不确定为什么。

这是完整的代码:

#include <iostream>
#include <utility>
#include <memory>

struct Node {
    int data;
    std::unique_ptr<Node> next = nullptr;
    Node* previous = nullptr;

    Node(const int& x, std::unique_ptr<Node>&& p = nullptr, Node* previous = nullptr) :
        data(x),
        next(std::move(p)),
        previous(previous){}
};
std::unique_ptr<Node> head = nullptr;
Node* tail = nullptr;

void print() {
    for (auto loop = head.get(); loop != nullptr; loop = loop-> next.get()) {
        std::cout << loop->data << " ";
    }
    std::cout << "\n";
}

void push_back(const int& theData) {
    std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);
    newNode->previous = tail;

    if (head == nullptr) {
        head = std::move(newNode);
        tail = head.get();
    }

    else {
        tail->next = std::move(newNode);
        tail = tail->next.get();
    }
}

void push_front(const int& theData) {
    head = std::make_unique<Node>(theData, std::move(head), nullptr);

    if (head->next == nullptr) {
        tail = head.get();
    }
}

void insert_at_position(int pos, const int& theData) {
    if (pos == 1) {
        push_front(theData);
        return;
    }

    auto current = head.get();
    std::unique_ptr<Node> newNode = std::make_unique<Node>(theData);

    for (int i = 1; i < pos; i++) {
        current = current->next.get();
    }

    if (current->next != nullptr) {
        newNode->next = std::move(current->next);
        newNode->previous = std::move(current->previous);
        current->next = std::move(newNode);
        current->previous = newNode.get();
    }

    else {
        push_back(theData);
        return;
    }
}

void pop_front() {
    head = std::move(head->next);

    if (!tail) {
        tail = head.get();
    }
}

void pop_back() {
    if (!head) return;

    auto current = head.get();
    Node* prev = nullptr;

    while (current->next != nullptr) {
        prev = current;
        current = current->next.get();
    }
    tail = prev;
    prev->next = nullptr;
}

void erase(int pos) {
    if (pos == 1) {
        pop_front();
        return;
    }

    auto current = head.get();
    Node* previous = nullptr;

    for (int i = 1; i < pos; i++) {
        previous = current;
        current = current->next.get();
    }
    previous->next = std::move(current->next);
}





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(4, 8);
    print();

    insert_at_position(2, 3);
    print();

    erase(1);
    print();

    erase(2);
    print();

    std::cin.get();

}

尤其是主行中的这一行:insert_at_position(1, 1);在应该1 1 2 4的时候给了我1 2 4

0 个答案:

没有答案