C++ 在双链表上插入函数

C++ 在双链表上插入函数,c++,pointers,doubly-linked-list,C++,Pointers,Doubly Linked List,我有一个双链表的insert函数,在我尝试在给定的索引处插入一个新节点之前,这个函数大部分都在工作。我在将其正确链接到前后的节点时遇到了问题,如果有人知道原因的话,我在尝试分配我将在代码中指出的其中一个点时会不断出错: void insert(int index, ItemType& item) { int pos = 0; Node* current = new Node; Node* n = new Node; n->info = i

我有一个双链表的insert函数,在我尝试在给定的索引处插入一个新节点之前,这个函数大部分都在工作。我在将其正确链接到前后的节点时遇到了问题,如果有人知道原因的话,我在尝试分配我将在代码中指出的其中一个点时会不断出错:

  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++;


  }
}
void插入(整数索引、项目类型和项目)
{
int pos=0;
节点*当前=新节点;
Node*n=新节点;
n->info=项目;
如果(索引>=0&&index-next=NULL;
n->prev=NULL;
大小++;
返回;
}
else if(索引==0)
{
n->prev=NULL;
n->next=头部;
头部->上一个=n;
水头=n;
大小++;
返回;
}
else if(索引==大小)
{
n->next=NULL;
n->prev=尾部;
tail->next=n;
尾=n;
大小++;
返回;
}
否则如果(索引<大小/2)
{
电流=水头;
while(pos!=索引)
{
当前=当前->下一步;
pos++;
}
}
否则如果(索引>大小/2)
{
int endpos=尺寸-1;
电流=尾部;
while(endpos!=索引)
{
当前=当前->上一个;
endpos--;
}
}
n->next=当前;
current->prev->next=n;//这里是代码中断的地方,不知道为什么。
n->prev=当前->上一个;
当前->上一个=n;
大小++;
}
}
因此,代码在当前->上一->下一个=n语句处中断,说明存在访问冲突写入位置。因此,我不确定这是否正确编码,或者我是否在早期代码中的指定任务中出错。如果有人知道为什么要这样做,并能为我指出正确的方向,那将非常棒。谢谢。

n,

  • index=size/2
    时,代码失败
  • 当有两个元素(大小==2)并且尝试在位置1插入时,则
    current->prev->next=n;
    没有意义


    执行其中一项更改
    否则如果(index=size/2)

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

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

    Node* current;
    
    而不是

    Node* current = new Node;
    

    太好了,这太完美了,修好了。非常感谢。