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