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

时间:2013-11-05 08:50:43

标签: c++ deque

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

1 个答案:

答案 0 :(得分:1)

这是在头部之前/之后插入节点的一些代码。如果那就是你要找的东西。

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;
}