【发布时间】: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