gpt4 book ai didi

C++ 删除队列中的节点

转载 作者:行者123 更新时间:2023-11-30 04:40:39 24 4
gpt4 key购买 nike

问题 1:删除列表中的一个节点 > 3

描述:

删除七个节点列表中的第六个节点,结果只打印第一个和最后一个节点。

可用节点指针:*下一个_, *上一个_, *数据_

删除指定节点的函数在LinkedList.cpp中名称:删除节点。

遍历链表打印节点的函数在main.cpp中名称:打印所有节点

可能的解决方案:

遍历打印节点时可以访问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;
}

最佳答案

这是你的问题:

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->prev_ 没有分配好。但是将它分配给 first_ 并不是解决方案。您应该检查您的其他方法(可能是 AddNode)以了解为什么您的 Current->prev_ 是错误的。

关于C++ 删除队列中的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/919458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com