问题1:在列表中的节点中删除> 3
说明
删除七个列表中的第六个节点,导致仅打印第一个节点 和最后一个节点。
可用的节点指针: * next_,* prev_,* data _
删除指定节点的功能在LinkedList.cpp中 名称:DeleteNode。
遍历列表以打印节点的函数位于main.cpp中 名称:PrintAllNodes
可能的解决方案:
在遍历打印节点时,能够访问main中的Current-> prev_。
代码:
void LinkedList::DeleteNode( Node* node )
{
Node *Current = first_; // I want this to be my only Node Ptr Varaible Declaration.
if ( NULL == first_ )
std::cout << "Cannot delete from an empty list: \n";
//TRAVERSING WAS/IS A BAD IDEA.............................
while ( Current != NULL )
{
if ( Current->data_ == node->data_ )
{
//If Current isn't the head of the list, set prev to next
if ( Current != first_ )
{
Current->prev_ = first_; //statement that follows crashes if this is not assigned.
Current->prev_->next_ = Current->next_;
}
else
{
first_ = Current->next_;
if ( first_ != NULL )
first_->prev_ = NULL;
}
//If Current isn't the tail of the list, set next to prev
if ( Current->next_ != NULL )
Current->next_ = Current->prev_;
else if ( Current->prev_ != NULL )
Current->prev_->next_ = NULL;
listLen_--;
delete Current;
Current = NULL;
}
else
{
Current->prev_ = Current;
Current = Current->next_;
}
}
return;
}
main.cpp中的PrintAllNodes代码:
void PrintAllNodes( LinkedList *LinkedObject, long length = 0 )
{
const char *Names = NULL;
length = LinkedObject->GetListLength();
Node *GetNode = LinkedObject->GetFirstNode();
for ( signed short x = 0; x < length; x++ )
{
Names = static_cast< NameObject* >( GetNode->data_ )->GetName();
cout << Names << endl;
GetNode = GetNode->next_; // traversing
}
return;
}
答案 0 :(得分:2)
这是你的问题:
Current->prev_ = first_;
您正在做的是在当前连接第一个到最后一个节点之前断开所有节点! (在你的情况下是第七个)
你应该做的只有:
Current->prev_->next_ = Current->next_;
Current->next_->prev_ = Current->prev_; //I think you forgot this
delete Current;
Current = NULL;
如果没有
Current->prev_ = first_;
你遇到了崩溃,那是因为你的Current-&gt; prev_分配不好。 但是将它分配给first_不是解决方案。 你应该检查你的其他方法(可能是AddNode),看看你的Current-&gt; prev_为什么不好。