在双向链表上插入函数

时间:2014-03-18 17:20:12

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

所以我已经为双链表创建了这个插入函数,这个列表大部分工作直到我尝试在给定索引处插入新节点。我无法正确地将其正确地链接到节点之前和之后,如果有人能够理解为什么,当我尝试分配我在代码中指出的一点时,我会不断出错:< / p>

  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-&gt; prev-&gt; next = n语句处断开,表明存在访问冲突写入位置。因此,我不确定这是否编码正确,或者我是否在早期代码中的指点分配中搞砸了。如果有人知道它为什么这样做,并能指出我正确的方向,那将是非常棒的。感谢。

2 个答案:

答案 0 :(得分:1)

根据我的观察,

  1. index = size/2时,您的代码失败。
  2. 如果有两个元素(大小== 2),当您尝试在第1位插入时,current->prev->next = n;无意义

    执行其中一项更改else if (index <= size/2)else if (index >= size/2)

答案 1 :(得分:0)

如果current是列表中的第一个节点,则current->prev将为NULL,因此current->prev->next会导致问题。您应该检查current是否是此行之前列表中的第一项。

此外,您的代码会泄漏内存,因为您为new Node分配current并且您不删除它。由于您使用current来遍历列表而不是创建新节点,因此您应该将其声明为

Node* current;

而不是

Node* current = new Node;