【问题标题】:Insert Function on Doubly Linked List在双向链表上插入函数
【发布时间】:2014-03-18 17:20:11
【问题描述】:

所以我为双向链表提供了这个插入函数,该函数在我尝试在给定索引处插入新节点之前大部分时间都在工作。我无法将它正确链接到它之前和之后的节点,如果有人能明白为什么,当我尝试分配我将在代码中指出的点之一时,我会不断收到错误:

  void insert(int index, ItemType& item) 
  {

    int pos = 0;
    Node* current = new Node;
    Node* n = new Node;
    n->info = item;
    if (index >= 0 && index <= size)
    {
        if (size == 0)
        {
            head = n;
            tail = n;
            n->next = NULL;
            n->prev = NULL;
            size++;
            return;
        }
        else if (index == 0)
        {
            n->prev = NULL;
            n->next = head;
            head->prev = n;
            head = n;
            size++;
            return;
        }
        else if (index == size)
        {
            n->next = NULL;
            n->prev = tail;
            tail->next = n;
            tail = n;
            size++;
            return;
        }
        else if (index < size/2)
        {
            current = head;
            while(pos != index)
            {
            current = current->next;
            pos++;
            }

        }
        else if (index > size/2)
        {
            int endpos = size - 1;
            current = tail;
            while(endpos != index)
            {
            current = current->prev;
            endpos--;

            }
        }


    n->next = current;
    current->prev->next = n; // HERE is where the code breaks, don't know why.
    n->prev = current->prev;
    current->prev = n;
    size++;


  }
}

因此代码在 current->prev->next = n 语句处中断,说明存在访问冲突写入位置。所以我不确定这是否编码正确,或者我是否搞砸了早期代码中的分配。如果有人知道它为什么这样做并且可以为我指出正确的方向,那就太棒了。谢谢。

【问题讨论】:

    标签: c++ pointers doubly-linked-list


    【解决方案1】:

    根据我的观察,

    1. index = size/2 时您的代码失败。

    当有两个元素时(size == 2),当你尝试在位置 1 插入时,current-&gt;prev-&gt;next = n; 没有意义

    执行以下更改之一 else if (index &lt;= size/2)else if (index &gt;= size/2)

    【讨论】:

    • 太好了,这太完美了,修好了。非常感谢。
    【解决方案2】:

    如果current 是列表中的第一个节点,那么current-&gt;prev 将是NULL,所以current-&gt;prev-&gt;next 会导致问题。您应该检查current 是否是此行之前列表中的第一项。

    此外,您的代码会泄漏内存,因为您正在为 current 分配一个 new Node 而您没有删除它。由于您使用 current 在列表中移动而不是创建新节点,因此您应该将其声明为 just

    Node* current;
    

    而不是

    Node* current = new Node;
    

    【讨论】:

      猜你喜欢
      • 2012-02-18
      • 1970-01-01
      • 2022-11-16
      • 2012-09-29
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 2018-11-04
      • 1970-01-01
      相关资源
      最近更新 更多