我一直在尝试创建一个双向链接列表,其中每个插入的值都将按升序排序。我尝试编写一些代码,但代码似乎总是崩溃。
这是我得到的:
void DoublyList::insertInOrder(int insertItem)
{
Node *temp = new Node;
temp->setData(insertItem);
if (first == NULL)
first->setData(insertItem);
else
{
if (temp->getData() <= first->getData())
{
temp->setNextLink(first);
first->setPreviousLink(temp);
first = temp;
}
Node *curr = first;
while (curr->getNextLink() != NULL)
{
if (temp->getData() <= curr->getData())
{
curr->getPreviousLink()->setNextLink(temp);
temp->setPreviousLink(curr->getPreviousLink());
temp->setNextLink(curr);
curr->setPreviousLink(temp);
}
curr->setNextLink(temp);
temp->setPreviousLink(curr);
}
}
++count;
}
最佳答案
在你的代码中你有
if (first == NULL)
first->setData(insertItem);
如果 first
为 NULL
,取消引用它或调用它的任何成员函数将导致您的程序崩溃(并生成核心转储)
关于c++ - 双向链表按顺序插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28845772/