1

Problem1: リスト内のノードの削除 > 3

説明:

7 つのリストから 6 番目のノードを削除すると、最初と最後のノードのみが出力されます。

利用可能なノード ポインタ: *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;
}
4

1 に答える 1

2

これはあなたの問題です:

Current->prev_  = first_;

あなたがやっていることは、現在の前のすべてのノードを切断し、最初から最後まで接続することです! (あなたの場合は7番目)

そこですべきことは、次のことだけです。

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_ が悪い理由を確認する必要があります。

于 2009-05-28T06:49:13.097 に答える