c++ - 在循环双向链表的第一个节点之前/之后插入的算法是什么?

标签 c++ deque

我一直在使用尾指针构建一个双端队列,我只是想知道如果我使用循环指针算法是否相同。在我看来,我将不必再跟踪尾指针,并且维护和更新列表会更容易。然而,令我震惊的是,第一个节点之前/之后的插入几乎是相同的,因为它是一个圆圈,所以在第一个节点和之后的节点之间没有区别。我的理解正确吗?如果您可以在此处演示示例或显示这些函数的伪代码,那就太好了。

最佳答案

这里有一些代码可以在头部之前/之后插入一个节点。如果这就是您要找的东西。

struct node
{
    int val;
    struct node *prev;
    struct node *next;
};

bool insert_after_head(struct node *head, int val)
{
    if(head == NULL)
        return false;

    struct node *temp = new node;
    if(temp == NULL)
        return false;

    temp->val = val;

    // build new links
    temp->prev = head;
    temp->next = head->next;

    // rebuild old links(watch the order)   
    head->next->prev = temp;
    head->next = temp;

    return true;
}

bool insert_before_head(struct node *head, int val)
{
    if(head == NULL)
        return false;

    struct node *temp = new node;
    if(temp == NULL)
        return false;

    temp->val = val;

    // build new links
    temp->next = head;
    temp->prev = head->prev;

    // rebuild old links(watch the order)
    head->prev->next = temp;
    head->prev = temp;

    return true;
}

关于c++ - 在循环双向链表的第一个节点之前/之后插入的算法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19784900/

相关文章:

c++ - 移动 std::deque 后引用/指针是否保证有效?

c++ - 创建和使用指向友元类方法的 func 指针

C++ 在工具栏中心拉伸(stretch) QLineEdit

c++ - std::deque 真的是线程安全的吗?

c++ - 了解 C++ 中的以下数据类型

java - 具有降序和升序的迭代器不起作用

c++ - 如何从 C++ 中的集合中随机选择一个元素?

c++ - 如何设计一个最近最近使用的缓存?

c++ - Boost::asio 这种奇怪的编码风格是什么?

python - 时间复杂度 : deleting element of deque