c++ - 双向链表节点插入位置

标签 c++ c++11 pointers data-structures doubly-linked-list

我目前正在研究双向链表,想请教一下。这是在特定位置插入节点的函数。

“temp”是指向节点的指针。

void insertpos(int value,int pos)
    {
        node *s;
        temp=new node;
        s=head;
        for(int i=0;i<pos-1;i++)
        {
            s=s->next;
        }
        temp->data=value;
        if(s->next==nullptr)
       {
           s->next=temp;
           temp->next=nullptr;
           temp->prev=s;
       }
       else
       {

           temp->next=s->next;
           temp->next->prev=temp;
           s->next=temp;
           temp->prev=s;
       }
    }

这行代码是什么意思 temp->next->prev=temp; 即使没有这个,该功能也能完美运行。

我知道要在特定位置插入,您需要从 head 开始并遍历到那个位置 (position-1) 并将该位置的下一个指针设置为 temp,将 temp 的下一个指针设置为下一个位置指针,将 temp 的前一个指针设置为位置.但这可以通过下面三行代码实现

temp->next=s->next;
       s->next=temp;
       temp->prev=s;

那么这行temp->next->prev=temp;有什么用 这条线是什么意思?

最佳答案

由于您在 ss->next 之间插入了一个节点,并且它是一个双向链表,所以 s->next previous 节点应指向新插入的节点,其间是 temp,因此 temp->next->prev=temp;

关于c++ - 双向链表节点插入位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51835082/

相关文章:

c++ - visual studio 2010 包含文件可以是 'see' 但无法编译

c++ - 如何在 C++ 中为 Raspberry PI USB UART 连接设置 termios 参数?

c++ - auto 如何决定变量的类型?

c - 类型转换结构指针

c++ - 指针除了存地址,怎么实现呢?

c++ - std::condition_variable 和 std::condition_variable_any 有什么区别?

c++ - 初始化一个固定的 C 数组成员结构

c++ - 我应该使用 QScopedPointer 还是 std::unique_ptr?

c++ - 在函数返回后释放动态分配的结构数组。

c++ - "(new Type [n]) + 1"返回什么?