在链表之前插入?

Insert before in linked list?

我正在尝试分析这段插入到之前给出的链表中的代码,但我认为代码中有一些多余的东西:

             //  new_n->next = p->next;
               // p->next = new_n;

我认为没有必要赋值 p->next = new_n;既然我们已经把 new_n 移到了 p->next 指向的地方? /

  template <typename Object>
    bool insertBeforeS(SNode<Object>* node, Object before, Object newValue) {
        SNode<Object> *new_n = new SNode<Object>(newValue);
        for (SNode<Object> * p = node; p != nullptr && p->next != nullptr; p = p->next) {
            if (p->data == before) {
                new_n->data = p->data;
                p->data = newValue;
                new_n->next = p->next;
                p->next = new_n;
                return true;
            }
        }

        return false;
    }

在列表中找到之前的值后,新节点将其值与 "before" 节点的值交换。

那么这个"before"节点应该指向新节点,新节点应该指向之前"before"节点指向的节点。

所以这些陈述

new_n->next = p->next;
p->next = new_n;

通过设置节点的下一个数据成员来完成所需的任务。

最初

| before-value| pointer to the next node|

新节点

| new-value | nullptr |

然后交换值

| new-value| pointer to the next node|
| before-value | nullptr |

然后在这条语句之后

new_n->next = p->next;

我们有

| new-value| pointer to the next node|
| before-value | pointer to the next node |

然后在这条语句之后

p->next = new_n;

我们有

| new-value| pointer to the new node |
| before-value | pointer to the next node |

注意函数在没有找到之前值的节点时会发生内存泄漏